Erik Erik - 10 months ago 53
Node.js Question

How to write file if parent folder doesn't exist?

I need to write file to the following path:

fs.writeFile('/folder1/folder2/file.txt', 'content', function () {


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?

Answer Source

Use mkdirp in combination with path.dirname first.

var mkdirp = require('mkdirp');
var fs = require('fs');
var getDirName = require('path').dirname;

function writeFile(path, contents, cb) {
  mkdirp(getDirName(path), function (err) {
    if (err) return cb(err);

    fs.writeFile(path, contents, cb);

If the whole path already exists, mkdirp is a noop. Otherwise it creates all missing directories for you.

This module does what you want: . 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.