I need to write file to the following path:
fs.writeFile('/folder1/folder2/file.txt', 'content', function () {…});
But '/folder1/folder2'
path may not exists. So I get the following error:
message=ENOENT, open /folder1/folder2/file.txt
How can I write content to that path?
writeFileSync() creates a new file if the specified file does not exist. Also the 'readline-sync' module is used to enable user input at runtime.
As of Node v10, this is built into the fs.mkdir function, which we can use in combination with path.dirname:
var fs = require('fs'); var getDirName = require('path').dirname; function writeFile(path, contents, cb) { fs.mkdir(getDirName(path), { recursive: true}, function (err) { if (err) return cb(err); fs.writeFile(path, contents, cb); }); }
For older versions, you can use mkdirp:
var mkdirp = require('mkdirp'); var fs = require('fs'); var getDirName = require('path').dirname; function writeFile(path, contents, cb) { mkdirp(getDirName(path), function (err) { if (err) return cb(err); fs.writeFile(path, contents, cb); }); }
If the whole path already exists, mkdirp
is a noop. Otherwise it creates all missing directories for you.
This module does what you want: https://npmjs.org/package/writefile . Got it when googling for "writefile mkdirp". This module returns a promise instead of taking a callback, so be sure to read some introduction to promises first. It might actually complicate things for you.
The function I gave works in any case.
I find that the easiest way to do this is to use the outputFile() method from the fs-extra module.
Almost the same as writeFile (i.e. it overwrites), except that if the parent directory does not exist, it's created. options are what you'd pass to fs.writeFile().
Example:
var fs = require('fs-extra'); var file = '/tmp/this/path/does/not/exist/file.txt' fs.outputFile(file, 'hello!', function (err) { console.log(err); // => null fs.readFile(file, 'utf8', function (err, data) { console.log(data); // => hello! }); });
It also has promise support out of the box these days!.
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