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); }
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.
mkdir() Method. The fs. mkdir() method i Node. js is used to create a directory asynchronously.
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 }); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With