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 a file in a subdirectory within the data subdirectory. However I am getting the following error:
{ [Error: ENOENT, open 'D:\data\tmp\test.txt'] errno: 34, code: 'ENOENT', path: 'D:\\data\\tmp\\test.txt' }
The code is as follows:
var fs = require('fs');
fs.writeFile("tmp/test.txt", "Hey there!", function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});
Can anybody help me in finding out how to make Node.js create the directory structure if it does not exits for writing to a file?
Node > 10.12.0
fs.mkdir now accepts a
{ recursive: true }option like so:or with a promise:
Notes,
In many case you would use
fs.mkdirSyncrather thanfs.mkdirIt 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.