Create Directory When Writing To File In Node.js
If you don't want to use any additional package, you can call the following function before creating your file:
var path = require('path'),
fs = require('fs');
function ensureDirectoryExistence(filePath) {
var dirname = path.dirname(filePath);
if (fs.existsSync(dirname)) {
return true;
}
ensureDirectoryExistence(dirname);
fs.mkdirSync(dirname);
}
Node > 10.12.0
fs.mkdir now accepts a { recursive: true }
option like so:
// Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist.
fs.mkdir('/tmp/a/apple', { recursive: true }, (err) => {
if (err) throw err;
});
or with a promise:
fs.promises.mkdir('/tmp/a/apple', { recursive: true }).catch(console.error);
Notes,
In many case you would use
fs.mkdirSync
rather thanfs.mkdir
It is harmless / has no effect to include a trailing slash.
mkdirSync/mkdir no nothing harmlessly if the directory already exists, there's no need to check for existence.
Node <= 10.11.0
You can solve this with a package like mkdirp or fs-extra. If you don't want to install a package, please see Tiago Peres França's answer below.
With node-fs-extra you can do it easily.
Install it
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 four ways.
Async/await
const fse = require('fs-extra');
await fse.outputFile('tmp/test.txt', 'Hey there!');
Using Promises
If you use promises, this is the code:
const fse = require('fs-extra');
fse.outputFile('tmp/test.txt', 'Hey there!')
.then(() => {
console.log('The file has been saved!');
})
.catch(err => {
console.error(err)
});
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 has been saved!');
}
})
Sync version
If you want a sync version, just use this code:
const fse = require('fs-extra')
fse.outputFileSync('tmp/test.txt', 'Hey there!')
For a complete reference, check the outputFile
documentation and all node-fs-extra supported methods.
Shameless plug alert!
You will have to check for each directory in the path structure you want and create it manually if it doesn't exist. All the tools to do so are already there in Node's fs module, but you can do all of that simply with my mkpath module: https://github.com/jrajav/mkpath