Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writeFile does not create file

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.

like image 222
SubjectX Avatar asked Nov 13 '17 11:11

SubjectX


People also ask

Does FS writeFile create file?

The fs. writeFileSync() is a synchronous method. The fs. writeFileSync() creates a new file if the specified file does not exist.

Does FS writeFile overwrite?

fs. writeFileSync and fs. writeFile both overwrite the file by default. Therefore, we don't have to add any extra checks.

Is FS writeFile a promise?

Promise version of fs. writeFile: Asynchronously writes data to a file, replacing the file if it already exists.

What is __ Dirname Nodejs?

It gives the current working directory of the Node. js process. __dirname: It is a local variable that returns the directory name of the current module. It returns the folder path of the current JavaScript file.


1 Answers

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)

like image 139
dpetrini Avatar answered Sep 28 '22 13:09

dpetrini