writeFile does not create file

SubjectX picture SubjectX · Nov 13, 2017 · Viewed 14.2k times · Source

Error code looks like:

{ Error: ENOENT: no such file or directory, open 'sad' errno: -2, code: 'ENOENT', syscall: 'open', path: 'sad' }

where 'sad' is the name of file I would like to write to and it doesn't exist.

Code looks like this:

fs.writeFile(filename, JSON_string, { flag: 'w' }, function(err){           
        if(err){
            return console.error(err);
        }           
        return JSON_string;
    });

There are other similar questions, but they are all wrong in their path, starting or not starting with /, I just want to write a file on root from where I run this node.js application (it is also initialized with npm in this directory..).

Running with

sudo node server4.js

Doesnt work either. Changing flags to w+ or wx or whatever, doesn't help. Code works if file exists.

Node v9+.

I need to use writeFile() function.

Answer

dpetrini picture dpetrini · Nov 13, 2017

This is working for me, please check if this works in your system:

var fs = require('fs')

fs.writeFile('./myfile.txt', 'Content to write', { flag: 'w' }, function(err) {
    if (err) 
        return console.error(err); 
    fs.readFile('./myfile.txt', 'utf-8', function (err, data) {
        if (err)
            return console.error(err);
        console.log(data);
    });
});

(besides writing it also reads to confirm)