I have a command line program in Javascript/Node.js that writes data to files.
I want to ask user confirmation to overwrite a file, if it already exists.
This fails:
function writeData (filename, data) {
var fs = require ('fs');
try {
fs.writeFileSync(filename, data, {flag: 'wx'});
} catch (e) {
if (e.code === "EEXIST") {
console.error ("File already exists.");
var readline = require('readline');
var rl = readline.createInterface(process.stdin, process.stdout);
rl.question("Overwrite? [yes]/no: ", function(answer) {
if(answer == "no") {
console.log ("Not overwritting, bye.");
process.exit (1);
}
else {
console.log ("Overwriting file.");
try {
fs.writeFileSync(filename, data, {flag: 'w'});
} catch (ee) { throw ee; }
rl.close();
}
});//question()
}
else { throw e; }
}//catch(e)
}
writeData ("/tmp/foo", "foo bar");
console.log ("do something else");
writeData ("/tmp/bar", "bar baz");
console.log ("done.");
process.exit(0);
This fails: the program does not wait for user input and exists.
NOTE: you need to run it twice to see the failure. the first time, it creates the files fine.
How should I proceed?