Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a directory if it doesn't exist using Node.js

Tags:

node.js

Is the following the right way to create a directory if it doesn't exist?

It should have full permission for the script and readable by others.

var dir = __dirname + '/upload'; if (!path.existsSync(dir)) {     fs.mkdirSync(dir, 0744); } 
like image 967
Whisher Avatar asked Jan 17 '14 20:01

Whisher


People also ask

How do you create a directory if it does not exist?

When you want to create a directory in a path that does not exist then an error message also display to inform the user. If you want to create the directory in any non-exist path or omit the default error message then you have to use '-p' option with 'mkdir' command.

Which method is used to create a directory in node JS?

mkdir() Method. The fs. mkdir() method i Node. js is used to create a directory asynchronously.


1 Answers

For individual dirs:

var fs = require('fs'); var dir = './tmp';  if (!fs.existsSync(dir)){     fs.mkdirSync(dir); } 

Or, for nested dirs:

var fs = require('fs'); var dir = './tmp/but/then/nested';  if (!fs.existsSync(dir)){     fs.mkdirSync(dir, { recursive: true }); } 
like image 76
chovy Avatar answered Oct 06 '22 02:10

chovy