2

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' }
1
  • 2
    You need to create target directory first. Commented Jul 18, 2017 at 8:54

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I've now added a few fs.mkdir() functions to run on startup if the directory doesn't exist. However, the directories aren't getting created, despite err in the callback not being truthy EDIT: WORKING NOW

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.