Try to check this code, It might work for you
const fs = require('fs');
const readline = require('readline-sync');
// Check if the file exists in the current directory, and if it is writable.
var path = ("file.txt"); // Path to your file
var data = output; // this variable contains some data to insert
fs.access(path, fs.constants.F_OK | fs.constants.W_OK, (err) => {
if (err) {
fs.writeFileSync('file.txt', output, 'utf-8'); //create a new file
} else {
try {
fs.writeFileSync(path, data, {flag:'a+'}); //append mode: adds text to actually existing file
} catch(err) {
console.error(err); //shows error if script can't add data
}
}
});
Also you must install readline-sync module from npm, also change 'path' and 'output' variables to make this work. After this if you will don't have file, script make a new one, if will exist, will insert actual data to your file without reseting it.
P.S: Sorry for my English language.