即使fs可以,require.resolve也找不到文件

时间:2018-09-28 20:39:25

标签: javascript node.js

我在使用node.js require.resolve时遇到问题,这种方法对于我首先运行的测试没有任何意义。

所以我的代码

let checkPluginCanLoad = (pluginName, pluginFile) => {
    return new Promise((res, rej) => {
        // build the plugin's class files path
        console.log(`looking for file at ${path}/${pluginName}/${pluginFile}`)
        let req = `${path}/${pluginName}/${pluginFile}`
        // check it exists blocking
        let fileState = fs.existsSync(`${req}.js`);
        if(fileState){
            console.log(`File ${req}.js ${fileState?"exists.":"does not exist."}`);
            // it exists try to load it
            let plugin = require.resolve(`${req}`);
            res(plugin);
         }else{
            // could not find or load the plugin
            rej(`Plugin is invalid can't find or load class for ${pluginFile}`);
        }
    });
}

变量设置为,path = "Plugins", pluginName = "TestPlugin", pluginFile = "TestPlugin";

我的输出是

Plugins from 'Plugins' have been loaded.    index.js:36 
looking for file at Plugins/TestPlugin/TestPlugin   Plugins.js:133 
File Plugins/TestPlugin/TestPlugin.js exists.    Plugins.js:138 failed to
load plugin 'TestPlugin' with error 'Error: Cannot find module  'Plugins/TestPlugin/TestPlugin''

最后一行 load plugin 'TestPlugin' ...来自该拒绝捕获系统。

因此,文件根据FileSystem存在,但解析器无法找到它。

我尝试在路径前加上../,以防它是从运行它的文件而不是应用程序目录中解析的, 我还尝试过在./前面加上它,以防它从应用程序目录中运行。

2 个答案:

答案 0 :(得分:1)

您需要添加./来告诉节点您正在定位本地文件。

let plugin = require.resolve(`./${req}`);

如果您忘记了节点,则会在steps described here中搜索

答案 1 :(得分:0)

这是由Windows中具有链接目录的符号链接引起的错误,

因此,对于我的开发环境,它从Git Repository目录连接目录。但是Node通过联结目录运行它,但是看到了原始目录。

E Git仓库位于D:\Projects\NodeAppRepo中 那么开发环境就在D:\Project\NodeApp\内部运行 我所有index.js, Core/, node_modules/都通过NodeApp内部的结点运行到git repo中的路径。

所以我在node index.js内运行D:\Project\NodeApp\,这时依次加载D:\Project\NodeApp\Core\Core.js,然后导入./Plugins.js,这是发生中断的地方,因为路径节点具有插件不是D:\Project\NodeApp\Core\Plugins.js,而是D:\Projects\NodeAppRepo\Core\Plugin.js