I am new to Node.js, so I'm not familiar with a lot of stuff. So basically I want to create a directory in the current working directory:
var mkdirp = require('mkdirp');
console.log("Going to create directory /tmp/test");
mkdirp('/tmp/test',function(err){
if (err) {
return console.error(err);
}
console.log("Directory created successfully!");
});
My current directory is C:\Users\Owner\Desktop\Tutorials\NodeJS
on Windows, which means I run node main.js
in that directory. (main.js is in C:\Users\Owner\Desktop\Tutorials\NodeJS
) After I run the code, it generates C:\tmp\test, which is in C:\
. But I want to create it in the current directory, so the result I want is C:\Users\Owner\Desktop\Tutorials\NodeJS\tmp\test
.
I just don't know how to do that...
You can use process.cwd()
to output the directory where your command has been executed (in your case, the directory where you run node main.js
) so your code might look like this:
var mkdirp = require('mkdirp');
var path = require('path');
console.log("Going to create directory /tmp/test");
mkdirp(path.join(process.cwd(), '/tmp/test'), function(err){
if (err) {
return console.error(err);
}
console.log("Directory created successfully!");
});
If you need just the directory where the main.js
file is located and not where you execute it (by calling node main.js
), you can use the __dirname
variable instead of process.cwd()
.
It's a good idea to use the path.join()
function to make sure the path delimiters are set correctly, especially when you're on a Windows system which may treat forward slashes as options.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments