itskdog
itskdog

Reputation: 221

Cannot create file with Node.js fs.appendFile

I have been trying to create a program which saves logs from a Slack team. I have most things working, but have so far been unable to use fs.appendFile() successfully, as the documentation claims it will create the file if it doesn't exist (and not to use fs.exists() or fs.access() beforehand to check), but I'm getting an ENOENT error.

This is my function:

var storeLog = function (username, type, channelName, message) {
    var pathArr = [loggingDir, type, channelName];
    var path = pathArr.join("/") + ".log";
    var fullMessage = username + ": " + message;
    fs.appendFile(path, fullMessage + "\r\n", function (err) {
        if (err && globalSettings.debugMode) {
            console.error("Error saving log:\n", err);
        }
        else if (globalSettings.debugMode) {
            console.info("Appended to " + path);
            console.info(fullMessage);
        }
    });

};

(globalSettings.debugMode is true)

The err variable has this result:

{ Error: ENOENT: no such file or directory, open 'D:\path\in\settings\Direct Message\username.log'
    at Error (native)
  errno: -4058,
  code: 'ENOENT',
  syscall: 'open',
  path: 'D:\\path\\in\\settings\\Direct Message\\username.log' }

Upvotes: 2

Views: 9069

Answers (1)

mjarraya
mjarraya

Reputation: 1226

fs.appendFile() requires you to create the directory in which it will create the file if it doesn't exist. It wont create the directory for you.

It is also the case for fs.createWriteStream() that you could also use with the a flag.

Upvotes: 11

Related Questions