Categories
JavaScript Answers

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

Spread the love

To write file if parent folder doesn’t exist with Node.js, we use the fs-extra module.

For instance, we write

const fs = require("fs-extra");
const file = "/tmp/this/path/does/not/exist/file.txt";

fs.outputFile(file, "hello!", (err) => {
  console.log(err);

  fs.readFile(file, "utf8", (err, data) => {
    console.log(data);
  });
});

to call the outputFile method to write 'hello!' to the file path.

And then we call readFile to read the file path in the outputFile callback.

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 *