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

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

提交回复
热议问题