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

前端 未结 4 2352
名媛妹妹
名媛妹妹 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: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);
    }
    

提交回复
热议问题