Is there an alternative to require() in Node.JS? A "soft require" which tries to find a file but doesn't error if it isn't there

StackOverflow https://stackoverflow.com/questions/22743250

  •  24-06-2023
  •  | 
  •  

Domanda

I'm loading a config.json file using require('./config.json') but I don't want to require a config file if they want to pass command line arguments instead, or just use the defaults. Is there any way to try to load a JSON file this way but not spit out an error if it can't be found?

È stato utile?

Soluzione

For general modules, you can check for existence before trying to load. In the following path is whatever path you want to load and process() is a function performing whatever processing you'd like on your module:

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.
    }
});

And remember that path above must be an actual path, and not a module name to be later resolved by Node as a path.

For a JSON file specifically, with path and process having the same meanings as above:

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);    
});

You can also use try... catch but keep in mind that v8 won't optimize functions that have try... catch in them. With path and process meaning the same as above:

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.      
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top