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
first taking the full path including directory and extracting the directory
//Just for the sake of example
cwd=process.cwd()
filendir=path.resolve(cwd,'_site/assets/text','node.txt')
// Extracting directory name
mkdir=path.dirname(filendir)
Now make the directory, add option recursive:true as stated by @David Weldon
fs.mkdirSync(mkdir,{recursive:true})
Then make the file
data='Some random text'
fs.writeFileSync(filendir,data)
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);
}
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