fs.appendFile 但如果路径 *不* 存在则失败

fs.appendFile but fail if path does *not* exist

查看 fs 文档,我正在寻找一个可以与 fs.appendFile 一起使用的标志,如果路径 存在,则会引发错误.

如果路径已经存在,我看到与引发错误有关的标志,但我没有看到如果路径 存在则引发错误的标志 -

https://nodejs.org/api/fs.html

首先,我假设你的意思是 fs.appendFile(),因为你指的 fs.append() 不在 fs 模块中。

似乎没有打开文件的标志,如果文件不存在则附加 returns 错误。你可以自己写一个。以下是如何执行此操作的一般思路:

fs.appendToFileIfExist = function(file, data, encoding, callback) {
    // check for optional encoding argument
    if (typeof encoding === "function") {
        callback = encoding;
        encoding = 'utf8';
    }
    // r+ opens file for reading and writing. Error occurs if the file does 
    fs.open(file, 'r+', function(err, fd) {
        if (err) return callback(err);

        function done(err) {
            fs.close(fd, function(close_err) {
                fd = null;
                if (!err && close_err) {
                    // if no error passed in and there was a close error, return that
                    return callback(close_err);
                } else {
                    // otherwise return error passed in
                    callback(err);
                }
            });
        }

        // file is open here, call done(err) when we're done to clean up open file

        // get length of file so we know how to append
        fs.fstat(fd, function(err, stats) {
            if (err) return done(err);

            // write data to the end of the file
            fs.write(fd, data, stats.size, encoding, function(err) {
                done(err);
            });

        });
    });
}

当然,您可以在调用 fs.appendFile() 之前测试文件是否存在,但由于竞争条件,不建议这样做。相反,建议您在 fs.open() 上设置正确的标志,并在文件不存在时触发错误。