How to wait until in node js - save

I want to see if the file is downloaded in the download folder? After downloading the file has to be saved in another folder.
let files = fs.readdirSync('C:\\Users\\xyz\\Downloads')
let tmpfiles+= files.map(file =>file.split('.').pop()=='tmp'? 1:0)
if(tmpfiles<=0){await readSave()}
async function readSave() {
files = fs.readdirSync('C:\\Users\\xyz\\Downloads')
files.forEach(file => {
if (file.includes('abc') && file.includes('EGF') && file.split('.').pop() == 'json')) {
let flpath = 'C:\\Users\\xyz\\Downloads\\' + file
let filedestPath = path.join(dataDir, folderPath, `//${file}`)
let fldata = fs.readFileSync(flpath, 'utf-8')
fs.writeFile(filedestPath, JSON.stringify(fldata), () => removefile(flpath))
}
})
}
function removefile(flpath) {
fs.unlink(flpath, (err) => {
if (err) throw err
})
}

Related

IOS error: Media stream has no audio tracks createMediaStreamSource

I tried to mix remote audio tracks in one track and replace my local stream but I got the following error
InvalidStateError: Media stream has no audio tracks createMediaStreamSource
Note: This happen in IOS and I used sipjs, angular , Ionic, and IOSRTC
async mixNWayCall(nawayCall: NWayCall) {
var receivedTracks = [];
nawayCall.lines.forEach((line: Line) => {
if (line !== null && line !== undefined) {
const sessionDescriptionHandler = line.sipSession.sessionDescriptionHandler;
if (!(sessionDescriptionHandler instanceof Web.SessionDescriptionHandler)) {
throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");
}
const peerConnection = sessionDescriptionHandler.peerConnection;
if (!peerConnection) {
throw new Error("Peer connection closed.");
}
peerConnection.getReceivers().forEach((receiver) => {
if (receiver.track) {
receivedTracks.push(receiver.track);
}
});
}
});
let context = new AudioContext();
let allReceivedMediaStreams = new MediaStream();
nawayCall.lines.forEach((line: Line) => {
if (line !== null && line !== undefined) {
let mixedOutput = context.createMediaStreamDestination();
const sessionDescriptionHandler = line.sipSession.sessionDescriptionHandler;
if (!(sessionDescriptionHandler instanceof Web.SessionDescriptionHandler)) {
throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");
}
const senderPeerConnection = sessionDescriptionHandler.peerConnection;
if (!senderPeerConnection) { throw new Error("Peer connection closed."); }
senderPeerConnection.getReceivers().forEach((receiver) => {
receivedTracks.forEach((track) => {
allReceivedMediaStreams.addTrack(receiver.track);
console.log(receiver.track.id, ' receiver.track.id');
console.log(track.id, ' track.id');
if (receiver.track.id !== track.id) {
var sourceStream = context.createMediaStreamSource(new MediaStream([track]));
sourceStream.connect(mixedOutput);
}
});
});
senderPeerConnection.getSenders().forEach((sender) => {
nawayCall.mergeTracks.push(sender.track);
let senderSourceStream = context.createMediaStreamSource(new MediaStream([sender.track]));
senderSourceStream.connect(mixedOutput);
sender.replaceTrack(mixedOutput.stream.getTracks()[0])
});
senderPeerConnection.getSenders()[0].replaceTrack(mixedOutput.stream.getTracks()[0]);
}
});
nawayCall.lines.forEach(async (line: Line) => {
if (line.held) await this.lineService.onResume(line.id, true);
});
nawayCall.held = false;
if (nawayCall.media.mute)
await this.lineService.onNWayCallUnmute(nawayCall.id);
}
}
from the code in the description I got an error that no audio tracks and
I expected to mix audio tracks in one audio track then merge the call

Upload to Amazon S3 from public URL

I would like to use the AWS iOS SDK to upload an image directly from a public url to a S3 bucket.
My goal is to avoid downloading then uploading the image, which would be obviously slower.
I tried to naively pass the URL to AWSS3TransferUtility.uploadFile like so :
import AWSCore
import AWSS3
// ...
AWSS3TransferUtility.register(
with: AWSServiceManager.default().defaultServiceConfiguration!,
transferUtilityConfiguration: AWSS3TransferUtilityConfiguration(),
forKey: "foo"
)
let utility = AWSS3TransferUtility.s3TransferUtility(forKey: "foo")!
let imageURL = URL(string: "https://via.placeholder.com/150/")!
utility
.uploadFile(
imageURL,
bucket: "<bucket name>",
key: "bar.jpeg",
contentType: "image/jpg",
expression: nil,
completionHandler: nil)
.continueWith {
if let error = $0.error {
print("Error: \(error.localizedDescription)")
}
return nil
}
But it seems to accept only url of local files and return the error
The operation couldn’t be completed. (com.amazonaws.AWSS3TransferUtilityErrorDomain error 4.)
Any idea if this is possible and how ?
Based on #jarmod idead I was able to do it using a Lambda (simplified here) :
const https = require('https');
const AWS = require('aws-sdk');
const s3 = new AWS.S3();
function loadImage(url) {
return new Promise((resolve, reject) => {
https.get(url, (resp) => {
if(resp.statusCode > 200) {
reject('The image could not be loaded (HTTP ' + resp.statusCode + ')');
}
resp.setEncoding('binary');
let chunks = [];
resp.on('data', (chunk) => {
chunks.push(Buffer.from(chunk, 'binary'));
});
resp.on('end', () => {
let binary = Buffer.concat(chunks);
resolve(binary);
});
}).on("error", (err) => {
console.log("Error: " + err.message);
reject(err);
});
});
}
exports.handler = async (event, context, callback) => {
try {
const url = ...;
const bucket = ...;
const key = ...;
const buffer = await loadImage(url);
const destparams = {
Bucket: bucket,
Key: key,
Body: buffer,
ContentType: "image"
};
await s3.putObject(destparams).promise();
return "OK";
} catch(error) {
return error;
}
};
Calling a Lambda using AWSLambda is quite simple :
let lambda = AWSLambdaInvocationRequest()!
lambda.functionName = // Lambda name
lambda.invocationType = .requestResponse
let parameters: [String: Any] = [:] // Parameters to pass to the lambda
let payload = try! JSONSerialization.data(withJSONObject: parameters, options: [])
lambda.payload = payload
AWSLambda.default().invoke(lambda) { response, error in
//...
}

Angular 9 file downloaded corrupted

I'm using Angular 9 with HttpClient and File-Saver to download Files from server for now I'm trying to download Excel files
refindicateurService :
downloadIndicateurById(indicateurCriteria: IndicateurCriteria): Observable<Blob> {
console.log(indicateurCriteria);
return this.authHttp.post( this.settings.server.url + `/indicateur/reportingIndicateur`, indicateurCriteria , {responseType: 'blob'})
.pipe(map(res => res));
}
Download Function :
downloadFile(response: Response) {
console.log(response);
var blob = new Blob([this.getResponseBody(response)], { type: response.type });
this.removeBusy();
// let fileName: any = response.headers.get("etag");
importedSaveAs(blob, 'data.xslx');
}
Then I call it here :
exportIndicateurAsXls(id) {
let indicateurCriteria = new IndicateurCriteria();
indicateurCriteria.id = id;
this.addBusy();
this.refindicateurService.downloadIndicateurById(indicateurCriteria)
.subscribe(response => {
this.downloadFile(response);
this.removeBusy();
}, error => this.showError(error.status, JSON.parse(JSON.stringify(error)).message));
}
I get the file downloaded but corrupted when using 'arraybuffer' it gives undefined data
Fix :
downloadFile(response: Blob) {
this.removeBusy();
importedSaveAs(response, 'data.xslx');
}

Unable to generate excel file from XLSX in ionic

I am creating excel file from user data but unfortunately its not generating file and even don't know what is the error so I can at-least try to solve that error.
Specially this issue occur in iOS platform only.
Please find below code to generate excel file:
public createXSLX(): Promise<any> {
return new Promise((resolve) => {
let sheet = XLSX.utils.json_to_sheet(this.data);
let wb = {
SheetNames: ["export"],
Sheets: {
"export": sheet
}
};
let wbout = XLSX.write(wb, {
bookType: 'xlsx',
bookSST: false,
type: 'binary'
});
function s2ab(s) {
let buf = new ArrayBuffer(s.length);
let view = new Uint8Array(buf);
for (let i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
let blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });
resolve(blob);
});
}
This above function works very well in android but in iOS its not generation file from provided data.
How I call above function code :
onExportNew = function (toEmail) {
this.createXSLX().then((xclBlob) => {
let time = new Date().getTime();
let fileName: string = "roster_" + time + ".xlsx";
var fs = ''
if (this.platform.is('ios')){
fs = this.file.documentsDirectory;
}else{
fs = this.file.externalDataDirectory;
}
console.log("File Path:- ",fs)
this.file.writeFile(fs, fileName, xclBlob, true).then(() => {
let fp = fs + fileName;
let email = {
// to: 'lmahajan#cisco.com',
// cc: 'erika#mustermann.de',
// bcc: ['john#doe.com', 'jane#doe.com'],
to: toEmail,
attachments: [fp],
subject: 'Roster Excel File',
body: '<h1>PFA</h1>',
isHtml: true
};
this.emailComposer.open(email).then(() => {
this.showDone = true;
}).catch(() => {
let toast = this.toastCtrl.create({
message: 'Could not open email composer',
duration: 3000
});
toast.present();
});
}).catch(() => {
this.displayAlert('Error', 'error creating file at: ' + fs);
});
}).catch(() => {
console.log("Excel file creation error");
});
}
Guide me if missing anything in above code.
Thanks in advance!

Content.once is not a function

I try to push a file to the IPFS, and I have converted to the Buffer. I got this error " content.once is not a function".
I am using this library in node.
var Buffer = require('buffer/').Buffer;
const doc = new jsPDF();
doc.fromHTML('test',10,10);
var covnertedBuffer = Buffer.from(doc.output('arraybuffer');
Then, I take the convertedBuffer and pass it to the IPFS api.
Any idea?
Updated test:
I have successfully pushed a file to the IPFS via the API with this code below.
const filename = '/home/administrator/Downloads/5HP8LWKHLV.pdf';
this.ipfsApi = ipfsApi('localhost', '5001');
let readablestream = fs.createReadStream(filename);
readablestream.on('readable', () => {
let result = readablestream.read();
console.log(result);
if (result) {
this.ipfsApi.files.add(result, function(err, files) {
if (err) {
res.json('err');
console.log(err);
}
res.json(files);
});
}
});
But, when I get the arrayBuffer from the doc.output and convert to the Buffer object and push to the IPFS and it failed. Please see below.
var _buffer = Buffer.from(req.buffer);
console.log('Converted to buffer:' + _buffer);
this.ipfsApi = ipfsApi('localhost', '5001');
this.ipfsApi.files.add(_buffer, function(err, files) {
if (!err) {
res.status(500);
console.log(err);
} else {
res.json(files);
res.status(200);
}
});
Thank you
Adding Buffer.from(your_buffer) to your buffer before doing ipfs push works.
ipfs.files.add(Buffer.from(put_your_buffer_here), (error, result) => {
if(error) {
console.error(error)
return
}
console.log("upload is successful");
});

Resources