I\'ve been tinkering with Node.js and found a little problem. I\'ve got a script which resides in a directory called data
. I want the script to write some data to
With node-fs-extra you can do it easily.
npm install --save fs-extra
Then use the outputFile
method. Its documentation says:
Almost the same as writeFile (i.e. it overwrites), except that if the parent directory does not exist, it's created.
You can use it in three ways:
const fse = require('fs-extra');
fse.outputFile('tmp/test.txt', 'Hey there!', err => {
if(err) {
console.log(err);
} else {
console.log('The file was saved!');
}
})
If you use promises, and I hope so, this is the code:
fse.outputFile('tmp/test.txt', 'Hey there!')
.then(() => {
console.log('The file was saved!');
})
.catch(err => {
console.error(err)
});
If you want a sync version, just use this code:
fse.outputFileSync('tmp/test.txt', 'Hey there!')
For a complete reference, check the outputFile documentation and all node-fs-extra supported methods.