Skip to content
Advertisement

How can i create a directory using Node.js?

how can i write the name and the path of my directory that i will to create in the same node command, like this and remove the path in my script >

node ./stack/create.js ./path/folderName

i´m trying to create a directory with this script but i want to remove const path in my script and set the path and name when i will to ran my script like this node ./stack/create.js ./path/folderName

my script

import fs from 'fs';

// path is where i will to create the directory and folderName is the name of the directory

// i want to write the name and path in my node command like this 

**`node ./stack/create.js ./stack/folderName`**

// i want remove this const because i dont want to open the script and change the path and name i prefer to write the path and name when i will to ran the script

const path = "./stack/004";
  
fs.access(path, (error) => {
  if (error) {
    fs.mkdir(path, {recursive: true}, (error) => {
      if (error) {
        console.log(error);
      } else {
        console.log("New Directory created successfully !!");
      }
    });
  } else {
    console.log("Given Directory already exists !!");
  }
});

i´m trying to create a directory with this script but i want to remove const path in my script and set the path and name when i will to ran my script like this node ./stack/create.js ./path/folderName

Advertisement

Answer

Try this way :

import fs from 'fs';

const path = process.argv[2];
  
fs.access(path, (error) => {
  if (error) {
    fs.mkdir(path, {recursive: true}, (error) => {
      if (error) {
        console.log(error);
      } else {
        console.log("New Directory created successfully !!");
      }
    });
  } else {
    console.log("Given Directory already exists !!");
  }
});
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement