I have an Angular service with a function for writing files away. The function can work on either an Ionic or Electron platform. For Ionic, it uses $cordovaFile for file actions and for Electron it uses the node fs library.
The function is as follows:
writeFile(filename: string, dirname: string, data: string | Blob, replace?: boolean): ngCordova.IFilePromise<ProgressEvent> {
if (this.isElectron) {
let promiseObj = this.$q.defer();
if (replace) {
try {
fs.unlinkSync('./' + dirname + '/' + filename);
}
catch (err) {
//err
}
}
fs.writeFile('./' + dirname + '/' + filename, data, 'binary', () => {
promiseObj.resolve(true);
});
return promiseObj.promise;
}
else {
return this.$cordovaFile.writeFile(cordova.file.dataDirectory + dirname, filename, data, replace);
}
};
When the Ionic platform is used, the function works fine and the downloaded files are written away correctly. However, when the Electron platform is used, all the downloaded files contain is the string [object Blob]
.
What is the correct way to write Blobs to files using fs?
MORE INFO
The data originally comes down as base64 in a JSON message but we then do this with it
let fileBlob = this.stringUtilityService.b64ToBlob(dataObj.Data[i].FileContents, 'image/png');
this.fileSystemService.writeFile(dataObj.Data[i].FileName, 'icons', fileBlob);
EXTRA MORE INFO
Here is the b64ToBlob() function, although as far as i can tell this function works fine and correctly returns a blob which the Ionic app correctly saves away and can display.
b64ToBlob(b64Data: string, contentType: string): any {
let sliceSize = 512;
let byteCharacters = atob(b64Data);
let byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
let slice = byteCharacters.slice(offset, offset + sliceSize);
let byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
let byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
let blob = new Blob(byteArrays, { type: contentType });
return blob;
}