user3126480
user3126480

Reputation:

Error writing a file using 'fs' in Node

I'm trying to write to a file using the following function:

function writeFile (data, callback) {
var fs = require('fs');
var now = new Date();

fs.writeFile(now.toISOString() + ".json", data, function(err) {

    if (err) {
        return console.log(err);
    } else {
        console.log(true);
    }
});
}

but im getting an error like this:

{ Error: ENOENT: no such file or directory, open 'C:\Users\Ruslan\WebstormProjects\communication-system\client\6\28\2017_19:47:55.json'
errno: -4058,
code: 'ENOENT',
syscall: 'open',
path: 'C:\\Users\\Me\\WebstormProjects\\blah-blah\\client\\6\\28\\2017_19:47:55.json' }

I'm trying to create a file every time I run the program, but that doesn't seem to work very well because it says file does not exist. Is there anything im doing wrong? BTW, im running this on windows

EDIT: It was indeed wrong file name that was bugging the saving process

Upvotes: 1

Views: 2220

Answers (1)

jfriend00
jfriend00

Reputation: 708036

When you call fs.writeFile() you have to pass it a filename/path:

  1. Where the parent directory in the path already exists.
  2. Where the path/filename contains only characters that are legal for your OS.

It appears you are likely failing both of these unless you've pre-created the directory: C:\Users\Ruslan\WebstormProjects\communication-system\client\6\28. And, if this is running on Windows, then you also can't use : in a filename.

Assume you actually want the path to be C:\Users\Ruslan\WebstormProjects\communication-system\client and what the filename to be based on your now.toISOString(), the usual work-around is to replace path separators and other invalid filename characters with safe characters to you convert your now.toISOString() to something that is always a safe filename. In this case, you could do this:

// replace forward and back slashes and colons with an underscore
// to make sure this is a legal OS filename
let filename = now.toISOString().replace(/[\/\\:]/g, "_") + ".json";

fs.writeFile(filename, ....)

Upvotes: 5

Related Questions