My current setup:
Convert canvas to blob.
Ask the user for a file path.
Save the blob at the location given by the user.
However, I can't get step 3 to work. I'm currently trying to use fs to do the job, but it doesn't really seem to save the file.
Current code:
canvas.toBlob(blob => {
remote.dialog.showSaveDialog({ defaultPath: "file.png" }).then((canceled, filepath) => {
if (filepath) { // Using filepath because canceled is always true for some reason
blob.arrayBuffer().then(arrayBuffer => {
console.log(arrayBuffer);
fs.writeFile(filepath, Buffer.from(arrayBuffer), err => {
if (err) throw err;
});
});
}
});
}, "image/png");
Are there any flaws in my code? I tried changing the Buffer to Uint8Array and Int8Array, but they didn't work either.
I solved the problem by changing canceled/filepath argument into one result argument which holds all of them, turns out I was just using showSaveDialog in a wrong way.
Related
I download an OpenAPI file from localhost and convert it to .json. It becomes something like this:
"components":{"responses":{"r200":{"content":{"application/json":{"schema":{"properties" ....
I'm doing this using this JavaScript code:
const processData = async () => {
const req = await axios.get('http://localhost:5004/swagger');
let reqJson = JSON.stringify(req.data);
fs.writeFile('swagger.json', reqJson, (err) => {
if (err) throw err;
})
}
processData()
If there are any changes in the OpenAPI file on localhost, I want to download it, convert to .json, save it as a new file and compare with the original swagger.json. It will be the same to previous code, but
fs.writeFile('newSwagger.txt' ....
And changes has to be in error field in url.
Question: How can I compare these files, and show any changes in a popup on a web site like:
Attention: there is changes in Backend API:
Missing api/xxx/yyy
Added api/zzz/yyy
I am creating a discord bot (irrelevent) that sends images into the chat. The user can type out the name of the image without needing to type the file extention. The problem is that the bot doesn't know what the file extention is so it will crash if the picture is a .jpg and the program was expecting a .png. Is there a way to make the program not require a file extention to open the file?
let image = imageName;
message.channel.send({ files: [`media/stickers/${imageName}.png`] });
Unfortunately, the extension of the filename is required. You know file.mp4 and file.mp3 is entirely different.
However, you can use a try-except and a for loop to get the correct file!
I would suggest:
let image = imageName;
let extensions = [".png", ".jpg", "gif"] // All the extensions you can think of
const pass = () => {}
for (const extension of extensions) {
try {
message.channel.send({ files: [`media/stickers/${imageName}${extension}`] }); // successfully get file and send
break
} catch(error) {
pass() // do nothing, and go back to the loop and test other extension
}
}
I haven't tried that before, and I am a Python programmer. But I hope you get the idea.
Using fs - specifically the Promise version of fs, makes this quite simple
import { readdir } from 'fs/promises';
const getFullname = async (path, target) =>
(await readdir(path))
.find(file =>
file === target || file.split('.').slice(0,-1).join('.') === target
);
try {
const actualName = await getExtension('media/stickers', imageName);
if (!actualName) {
throw `File ${imageName} not found`;
}
message.channel.send({ files: [`media/stickers/${actualName}`] });
} catch(error) {
// handle your errors here
}
You can pass in the name with or without the extension and it will be found - note, this is NOT case insensitive ... so XYZ won't match xyz.jpg - easily changed if you need case insensitivity
There are only a few known image extensions like jpg, png, gif, jpeg. Maybe try and fetch the file with best guess extension, if it throws exception try the next format.
I am making an image compressor. In the image you see a simple design with a dragon drop to fill in ur files. But i want to download the image i keep getting one error (displayed below).
[This is what i got so far.][1]
[1]: https://i.stack.imgur.com/2RJ3v.png
This is my download funtion but when i press the button to download i keep getting 1 error
function download(file, res) {
console.log(file);
var fdata = new FormData()
fdata.append('upload_preset', 'image_name')
fdata.append('file', file)
// converts the picture and instant download the new image.
imageConversion.compressAccurately(file, 50).then(res=>{
console.log(res)
imageConversion.downloadFile(res)
})
}
Error:
conversion.js:1 Uncaught (in promise) Error: compressAccurately():
First arg must be a Blob object or a File object.
I tried a lot of things but i can't really figure it out. Someone got any idea how to solve this?
I figured it out. I had to add an Array and make the file excisable for all functions.
function handleFiles(files) {
window.files = files;
files = [...files];
files.forEach(previewFile);
}
function download() {
Array.from(files).forEach((element) => {
// converts the picture and instant download the new image.
imageConversion.compressAccurately(element, 50).then((res) => {
console.log(res);
imageConversion.downloadFile(res, 'test');
});
});
}
I am trying to read a text file that is in the source(src) folder of the react project(creat-react-app), manipulate the values and write back the new value to the same text file.
I am unable to read the values from the file, even though the code that reads the file is logging out old data, not sure where is that coming from. Because even if change the data in the text file directly, it doesn't read the new value.
I am using a package called browserify-fs (https://www.npmjs.com/package/browserify-fs) for reading and writing to a file.
var fs = require('browserify-fs');
var reader = new FileReader();
export const getData = () => {
let initialString = "abcd";
fs.readFile('file.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log(initialString + data.toString());
});
};
export const writeData = () => {
let data = "abcd";
fs.writeFile("file.txt", data, err => {
// In case of a error throw err.
if (err) throw err;
});
}
Does it have to do something with webpack-loader for importing the types of file for the build or is it related specifically to create-react-app package which defines the files and folder structure for auto-importing types of files?
I am still not sure what is the actual issue causing. Any help would be appreciated.
P.S: I know using CRUD operations on the browser is not a recommended practice, just using for a personal project(learning purpose).
I have following code working for every file except one that keeps hanging without emitting end or error events (I tried other stream events too).
const fs = require('fs');
const rs = fs.createReadStream(filePath, {
encoding: 'base64',
});
rs.on('data', () => {
console.log('data');
});
rs.on('end', () => {
console.log('end');
});
rs.on('error', e => {
console.log('error', e);
});
If I move read point with start option to 1 instead of 0 it works properly. Same if highWaterMark is set to value other than default. It doesn't really help as it seems it can fail with other "corrupted" file.
It seems like Node bug, but maybe there's something I'm missing here.
I'll post file in here too, but first I need to strip it to down to only corrupting part as it's somewhat private.
Update
Here's file to recreate the issue:
http://s3.eu-west-1.amazonaws.com/jjapitest/file
Update
Here's interactive demo of the issue:
https://repl.it/repls/AnimatedDisguisedNumerator