How to properly write json file only if the file doesn't exist.
fs.exists method is deprecated so I won't use that.
Any idea?
How to properly write json file only if the file doesn't exist.
fs.exists method is deprecated so I won't use that.
Any idea?
You just need to pass the 'wx' flags to fs.writeFile(). This will create and write the file if it does not exist or will return an error if the file already exists. This is supposed to be free of race conditions which fs.exist() and fs.access() are subject to because they don't have the ability to test and create the file in an atomic action that cannot be interrupted by any other process.
Here's an encapsulated version of that concept:
// define version of fs.writeFile() that will only write the file
// if the file does not already exist and will do so without
// possibility of race conditions (e.g. atomically)
fs.writeFileIfNotExist = function(fname, contents, options, callback) {
if (typeof options === "function") {
// it appears that it was called without the options argument
callback = options;
options = {};
}
options = options || {};
// force wx flag so file will be created only if it does not already exist
options.flag = 'wx';
fs.writeFile(fname, contents, options, function(err) {
var existed = false;
if (err && err.code === 'EEXIST') {
// This just means the file already existed. We
// will not treat that as an error, so kill the error code
err = null;
existed = true;
}
if (typeof callback === "function") {
callback(err, existed);
}
});
}
// sample usage
fs.writeFileIfNotExist("myFile.json", someJSON, function(err, existed) {
if (err) {
// error here
} else {
// data was written or file already existed
// existed flag tells you which case it was
}
});
See a description of the flag values you can pass to fs.writeFile() here in the node.js doc.