Alexander Mills
Alexander Mills

Reputation: 100080

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

Looking through the fs docs, I am looking for a flag that I can use with fs.appendFile, where an error will be raised if the path does not exist.

I am seeing flags that pertain to raising errors if the path does already exist, but I am not seeing flags that will raise errors if the path does not exist -

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

Upvotes: 4

Views: 1294

Answers (1)

jfriend00
jfriend00

Reputation: 707466

First off, I assume you mean fs.appendFile(), since the fs.append() you refer to is not in the fs module.

There does not appear to be a flag that opens the file for appending that returns an error if the file does not exist. You could write one yourself. Here's a general idea for how to do so:

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);
            });

        });
    });
}

You could, of course, just test to see if the file exists before calling fs.appendFile(), but that is not recommended because of race conditions. Instead, it is recommended that you set the right flags on fs.open() and let that trigger an error if the file does not exist.

Upvotes: 3

Related Questions