仅当文件不存在时如何正确写入json文件。
fs.exists
方法已过时,因此我将不使用它。
任何想法?
您只需要将'wx'
标志传递给即可fs.writeFile()
。如果文件不存在,它将创建并写入文件;如果文件已存在,则将返回错误。这应该是免费的比赛条件,fs.exist()
并fs.access()
受,因为他们没有能力来测试并创建不能由任何其他进程被中断的原子操作的文件。
这是该概念的封装版本:
// 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
}
});
请fs.writeFile()
在node.js doc中查看可传递给此处的标志值的描述。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句