Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 () {…}); 

But '/folder1/folder2' 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?

like image 476
Erik Avatar asked May 01 '13 10:05

Erik


People also ask

Does writeFileSync create file?

writeFileSync() creates a new file if the specified file does not exist. Also the 'readline-sync' module is used to enable user input at runtime.


2 Answers

As of Node v10, this is built into the fs.mkdir function, which we can use in combination with path.dirname:

var fs = require('fs'); var getDirName = require('path').dirname;  function writeFile(path, contents, cb) {   fs.mkdir(getDirName(path), { recursive: true}, function (err) {     if (err) return cb(err);      fs.writeFile(path, contents, cb);   }); } 

For older versions, you can use mkdirp:

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: https://npmjs.org/package/writefile . 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.

like image 88
Myrne Stol Avatar answered Sep 22 '22 10:09

Myrne Stol


I find that the easiest way to do this is to use the outputFile() method from the fs-extra module.

Almost the same as writeFile (i.e. it overwrites), except that if the parent directory does not exist, it's created. options are what you'd pass to fs.writeFile().

Example:

var fs = require('fs-extra'); var file = '/tmp/this/path/does/not/exist/file.txt'  fs.outputFile(file, 'hello!', function (err) {     console.log(err); // => null      fs.readFile(file, 'utf8', function (err, data) {         console.log(data); // => hello!     }); }); 

It also has promise support out of the box these days!.

like image 30
tkarls Avatar answered Sep 24 '22 10:09

tkarls