I’m trying to create a json file using my website (that I will later deploy). This is the code I’m using
saveFile = (i, data) => {
var filename = `${i}_may.json`;
var folder_list = ["desktop", "data", filename];
var dir = ".";
folder_list.forEach(function (x, i) {
dir = require("path").join(dir, `${x}`);
if (!fs.existsSync(dir)) {
fs.writeFileSync(dir, JSON.stringify(data));
}
});
};
But I keep getting this error
Error: ENOENT: no such file or directory, open 'desktopdata'
errno: -4058,
syscall: 'open',
code: 'ENOENT',
path: 'desktop\data'
Of course the folder exists in my desktop. Is there a way to make it works but in local and after the deployment?
2
Answers
To save a file to
[current_dir]desktopdata
, you can use the following code:Notice that the correct way to declare the path is to use
require("path").join('desktop','data',filename)
, which ensures that the path is properly constructed regardless of the platform you are running on.I dont see why you are using
forEach
if you ultimately want to execute the writing only once.Also, using an absolute path is a better choice here. Regardless of your working dir, the script will always save the file in the correction location.