How to check in node if module exists and if exists to load?

前端 未结 4 2337
名媛妹妹
名媛妹妹 2020-12-15 02:20

I need to check if file/(custom)module js exists under some path. I tried like

var m = require(\'/home/test_node_project/per\');
but it throws error

相关标签:
4条回答
  • 2020-12-15 03:02

    You can just check is a folder exists by using methods:

    var fs = require('fs');
    
    if (fs.existsSync(path)) {
        // Do something
    }
    
    // Or
    
    fs.exists(path, function(exists) {
        if (exists) {
            // Do something
        }
    });
    
    0 讨论(0)
  • 2020-12-15 03:08

    Require is a synchronous operation so you can just wrap it in a try/catch.

    try {
        var m = require('/home/test_node_project/per');
        // do stuff
    } catch (ex) {
        handleErr(ex);
    }
    
    0 讨论(0)
  • 2020-12-15 03:10

    You can just try to load it and then catch the exception it generates if it fails to load:

    try {
        var foo = require("foo");
    }
    catch (e) {
        if (e instanceof Error && e.code === "MODULE_NOT_FOUND")
            console.log("Can't load foo!");
        else
            throw e;
    }
    

    You should examine the exception you get just in case it is not merely a loading problem but something else going on. Avoid false positives and all that.

    0 讨论(0)
  • 2020-12-15 03:10

    It is possible to check if the module is present, without actually loading it:

    function moduleIsAvailable (path) {
        try {
            require.resolve(path);
            return true;
        } catch (e) {
            return false;
        }
    }
    

    Documentation:

    require.resolve(request[, options])

    Use the internal require() machinery to look up the location of a module, but rather than loading the module, just return the resolved filename.

    Note: Runtime checks like this will work for Node apps, but they won't work for bundlers like browserify, WebPack, and React Native.

    0 讨论(0)
提交回复
热议问题