Pablo
Pablo

Reputation: 547

Is it possible to create a dir in Node like "mkdir -p" does?

Is it possible to use the fs API to create a directory and all necessary subdirectories like the -p parameter does when using the mkdir command?

Upvotes: 25

Views: 8564

Answers (3)

Dániel Mari
Dániel Mari

Reputation: 589

Use fs.mkdirSync with the recursive: true option:

fs.mkdirSync('/tmp/a/apple', { recursive: true });

Upvotes: 57

Bilawal Hameed
Bilawal Hameed

Reputation: 256

You can also use a NPM package called fs-extra that conveniently allows you to do this:

const fs = require("fs-extra");

async function createFolder(folder) {
  try {
    await fs.ensureDirSync(folder); // guarantees the directory is created, or error.
  } catch (err) {
    throw new Error('You do not have the right permissions to make this folder.');
  }
}

Upvotes: 0

simon-p-r
simon-p-r

Reputation: 3751

You can either write your own version or use a module like mkdirp

Upvotes: 2

Related Questions