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

前端 未结 4 2357
名媛妹妹
名媛妹妹 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: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.

提交回复
热议问题