Create Directory When Writing To File In Node.js

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,

  1. In many case you would use fs.mkdirSync rather than fs.mkdir

  2. It is harmless / has no effect to include a trailing slash.

  3. 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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)