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.
The fs. writeFileSync() is a synchronous method. The fs. writeFileSync() creates a new file if the specified file does not exist.
fs. writeFileSync and fs. writeFile both overwrite the file by default. Therefore, we don't have to add any extra checks.
Promise version of fs. writeFile: Asynchronously writes data to a file, replacing the file if it already exists.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With