With node-fs-extra, you can do it easily.
Install it
npm install
Then use the outputFile method. Its documentation says:
Almost the same as writeFile (i.e. overwrites), except that if the parent directory does not exist, it is created.
You can use it in three ways:
Callback style
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!'); } })
Using promises
If you use promises , and I hope this is the code:
fse.outputFile('tmp/test.txt', 'Hey there!') .then(() => { console.log('The file was saved!'); }) .catch(err => { console.error(err) });
Sync version
If you want to sync the version, just use this code:
fse.outputFileSync('tmp/test.txt', 'Hey there!')
For full help, check the documentation of outputFile and all supported node-fs-extra methods .
lifeisfoo Aug 2 '17 at 16:09 on 2017-08-02 16:09
source share