writeFile does not create file
Asked Answered
W

1

19

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.

Wiliness answered 13/11, 2017 at 11:17 Comment(4)
hi, what do you have in "filename" variable?Delorenzo
I checked. Its working fine. what are u using in filenameXi
Use __dirname + filename for access to your file path.Maroc
As said in OP, file name is sad, which gets send to function parameter filename.Wiliness
D
14

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)

Delorenzo answered 13/11, 2017 at 11:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.