admin管理员组

文章数量:1315792

Here I am trying to create a directory using async function fs.mkdir using the below code but I am getting a error

ERROR: No such file or directory, mkdir 'C:\tmp\test';

var fs = require("fs");
console.log("Going to create directory /tmp/test");
fs.mkdir('/tmp/test',function(err){
    if (err) {
        return console.error(err);
    }
console.log("Directory created successfully!");
});

Any Help regarding this will be highly appreciated.

Here I am trying to create a directory using async function fs.mkdir using the below code but I am getting a error

ERROR: No such file or directory, mkdir 'C:\tmp\test';

var fs = require("fs");
console.log("Going to create directory /tmp/test");
fs.mkdir('/tmp/test',function(err){
    if (err) {
        return console.error(err);
    }
console.log("Directory created successfully!");
});

Any Help regarding this will be highly appreciated.

Share Improve this question asked Aug 22, 2016 at 18:04 abhishek taurabhishek taur 531 gold badge2 silver badges7 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

This error could happen if, for instance, the directory "/tmp" does not exist. If this is the case, you need before create "/tmp" and after "/tmp/test".

There is a package mkdirp that can help you:

So, the code will be:

    var mkdirp = require('mkdirp');

    mkdirp('/tmp/test', function (err) {
        if (err) console.error(err)
        else console.log('Done!')
    });

Try make a directory tmp in the same path as the script and it should work, else you must write the full path. If the tmp directory doesn't exist you must make that first.

Try using fs.mkdirSync and also check if the directory exists or not.

var checkIfDirectoryExists = function(dirPath, successCallback, errorCallback) {
    try {
        // Query the entry
        var stats = fs.lstatSync(dirPath);
        // Is it a directory?
        if (stats.isDirectory()) {
            successCallback();
        }
    } catch (e) {
        errorCallback();
    }
};

var mkdirIfNotExists = function(dirPath) {
    return new Promise(function(resolve, reject) {
        checkIfDirectoryExists(dirPath, function() {
            resolve();
        }, function() {
            fs.mkdirSync(dirPath);
            resolve();
        });
    });
};

本文标签: javascriptHow to create a directory in node js using fsmkdirStack Overflow