I have found an error writing a wrong variable, when writing the file, due to that error, the file has been written wrong, deleting everything that was in it, leaving it blank.
fs.writeFile(
path.join(__dirname,"../example/path/file.json") ,
JSON.stringify(var)
);
How can i make: "If error exist, dont try to write the file and throw an error via console"
You read the documentation and open/write to the file with the correct flags :
const fs = require('fs/promises');
async function writeFile(fn, content) {
const opts = {
// assuming that content is a string
encoding: 'utf8',
// 'wx' opens a file for writing.
// The file is created if it does not exist,
// and rejects if the file does exist.
flag: 'wx',
};
// returns undefined on success, or an error
return await fs
.writeFile(fn, content, opts)
.catch( err => err )
;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.