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?
Create directories recursively if they do not exist! (Zero dependencies)
Usage
Demo
Try It!
Explanations
{isRelativeToScript: true}
.path.sep
andpath.resolve()
, not just/
concatenation, to avoid cross-platform issues.fs.mkdirSync
and handling the error withtry/catch
if thrown to handle race conditions: another process may add the file between the calls tofs.existsSync()
andfs.mkdirSync()
and causes an exception.if (!fs.existsSync(curDir) fs.mkdirSync(curDir);
. But this is an anti-pattern that leaves the code vulnerable to race conditions. Thanks to @GershomMaes comment about the directory existence check.Here's part of Myrne Stol's answer broken out as a separate answer:
Use mkdirp in combination with
path.dirname
first.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.
You can use
stats
is afs.Stats
type of object, you may checkstats.isDirectory()
. Depending on the examination oferr
andstats
you can do something,fs.mkdir( ... )
or throw an error.Reference
Update: Fixed the commas in the code.
Perhaps most simply, you can just use the fs-path npm module.
Your code would then look like:
I find that the easiest way to do this is to use the outputFile() method from the fs-extra module.
Example:
It also has promise support out of the box these days!.