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) {
    } 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?

Problem courtesy of: Hirvesh


The standard for mkdir -p functionality is, the appropriately named, mkdirp. Package stats can be found here.

Solution courtesy of: David Weldon


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:

Discussion courtesy of: jrajav

Since I cannot comment yet, I'm posting an enhanced answer based on @tiago-peres-fran├ža fantastic solution (thanks!). His code does not make directory in a case where only the last directory is missing in the path, e.g. the input is "C:/test/abc" and "C:/test" already exists. Here is a snippet that works:

function mkdirp(filepath) {
    var dirname = path.dirname(filepath);

    if (!fs.existsSync(dirname)) {

Discussion courtesy of: micx

If you don't want to use any additional package, you can call the following function before creating your file:

function ensureDirectoryExistence(filePath) {
  var dirname = path.dirname(filePath);
  if (fs.existsSync(dirname)) {
    return true;

PS: "path" and "fs" are default node packages that need to be required. Remember to add the following to your code:

var path = require('path'),
    fs = require('fs');
Discussion courtesy of: Tiago Peres França

My advise is: try not to rely on dependencies when you can easily do it with few lines of codes

Here's what you're trying to achieve in 14 lines of code:

fs.isDir = function(dpath) {
    try {
        return fs.lstatSync(dpath).isDirectory();
    } catch(e) {
        return false;
fs.mkdirp = function(dirname) {
    dirname = path.normalize(dirname).split(path.sep);
        var pathInQuestion = dirname.slice(0,index+1).join(path.sep);
        if((!fs.isDir(pathInQuestion)) && pathInQuestion) fs.mkdirSync(pathInQuestion);
Discussion courtesy of: Alex C.

I just published this module because I needed this functionality.

It works like a wrapper around Node.js fs methods. So you can use it exactly the same way you would with fs.writeFile and fs.writeFileSync (both async and synchronous writes)

Discussion courtesy of: Amida

This recipe can be found in it's original form on Stack Over Flow.