Node.js - 如果文件不存在则写入json [不使用fs.exists()]

时间:2016-03-17 08:03:22

标签: node.js

如果文件不存在,如何正确编写json文件。

fs.exists方法已被弃用,因此我不会使用它。

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

您只需将'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() here in the node.js doc的标记值的说明。