Node.JS中是否有require()的替代方案?A「;“软要求”;它试图查找文件,但没有';如果不是',则不会出错;不在那里

Node.JS中是否有require()的替代方案?A「;“软要求”;它试图查找文件,但没有';如果不是',则不会出错;不在那里,node.js,config,require,Node.js,Config,Require,我正在使用require('./config.json')加载一个config.json文件,但是如果他们想传递命令行参数,或者只是使用默认值,我不想需要配置文件。是否有任何方法可以尝试以这种方式加载JSON文件,但如果找不到它,则不会抛出错误?对于常规模块,您可以在尝试加载之前检查是否存在。在下面的中,path是您想要加载的任何路径,process()是一个函数,它执行您想要在模块上执行的任何处理: var fs = require("fs"); fs.exists(path, functio

我正在使用
require('./config.json')
加载一个
config.json
文件,但是如果他们想传递命令行参数,或者只是使用默认值,我不想需要配置文件。是否有任何方法可以尝试以这种方式加载JSON文件,但如果找不到它,则不会抛出错误?

对于常规模块,您可以在尝试加载之前检查是否存在。在下面的
中,path
是您想要加载的任何路径,
process()
是一个函数,它执行您想要在模块上执行的任何处理:

var fs = require("fs");
fs.exists(path, function (exists) {
    if (exists) {
        var foo = require(path);
        process(foo);
    }
    else {
        // Whatever needs to be done if it does not exist.
    }
});
请记住,上面的
path
必须是实际路径,而不是稍后由节点解析为路径的模块名

具体而言,对于JSON文件,
path
process
具有与上述相同的含义:

fs.readFile(path, function (err, data) {
    if (err) {
        // Whatever you must do if the file cannot be read.
        return;
    }

    var parsed = JSON.parse(data);
    process(parsed);    
});
try {
    var foo = require(path);
    process(foo);
}
catch (e) {
    if (e.code !== "MODULE_NOT_FOUND")
        throw e; // Other problem, rethrow.
    // Do what you need if the module does not exist.      
}
您也可以使用
尝试。。。catch
但请记住,v8不会优化具有
try。。。捕捉它们中的
。具有
路径
过程
的含义与上述相同:

fs.readFile(path, function (err, data) {
    if (err) {
        // Whatever you must do if the file cannot be read.
        return;
    }

    var parsed = JSON.parse(data);
    process(parsed);    
});
try {
    var foo = require(path);
    process(foo);
}
catch (e) {
    if (e.code !== "MODULE_NOT_FOUND")
        throw e; // Other problem, rethrow.
    // Do what you need if the module does not exist.      
}

您可以首先测试该文件,如果它只是一个JSON,请使用
fs
手动加载它。在那里你可以检查文件是否存在。很好的解决方案!太糟糕了,节点没有像PHP那样的
include()
语句-