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?

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

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: https://github.com/jrajav/mkpath

I just published this module because I needed this functionality.

https://www.npmjs.org/package/filendir

note: It's the first time I make and publish a npm module. Please, create an issue on github if needed. Any comment for improvement is welcome.