Q:

Create Directory When Writing To File In Node.js

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?

A:

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);
}

A:

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);

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.

A:

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 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 so, 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 a sync version, just use this code:
fse.outputFileSync('tmp/test.txt', 'Hey there!')

For a complete reference, check the outputFile documentation and all node-fs-extra supported methods.

