Categories
JavaScript Answers

How to write file if parent folder doesn’t exist with Node.js?

Spread the love

Sometimes, we want to write file if parent folder doesn’t exist with Node.js.

In this article, we’ll look at how to write file if parent folder doesn’t exist with Node.js.

How to write file if parent folder doesn’t exist with Node.js?

To write file if parent folder doesn’t exist with Node.js, we can call mkdir to create the folder before creating the file in the folder.

For instance, we write

const fs = require('fs');
const getDirName = require('path').dirname;

fs.mkdir(getDirName(path), {
  recursive: true
}, (err) => {
  if (err) return cb(err);

  fs.writeFile(path, contents, (err) => {
    //...
  });
});

to call fs.mkdir with the folder path we want to create and an object that has recursive set to true to create the folder event if the parent folder doesn’t exist.

Then in the mkdir callback, we call writeFile to write the file to the given path.

Conclusion

To write file if parent folder doesn’t exist with Node.js, we can call mkdir to create the folder before creating the file in the folder.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *