Javascript要求

时间:2015-01-07 10:14:51

标签: javascript node.js

include.js文件包含

var test = function(){
    console.log("log from included file");
};

main.js文件包含

require('./include.js');
test();

当我尝试使用main.js命令运行node main.js时,显示

module.js:340
    throw err;
          ^
Error: Cannot find module 'include.js'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (d:\Nishada\test\main.js:1:63)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)

出现此错误的原因是什么?

3 个答案:

答案 0 :(得分:2)

您需要导出测试功能才能在main.js

中使用它
var test = function(){
    console.log("log from included file");
};

module.exports = test

main.js添加require如下

require('./include.js'); // assuming include.js is in same directory as main.js

如果您执行require('include.js'),则节点将在全局包中搜索include

答案 1 :(得分:2)

错误指的是找不到文件,请确保您的文件与main.js位于同一目录中并尝试:

include.js

module.exports = {
    test: function(){
        console.log("log from included file");
    }
}

main.js

var myInclude = require('include.js');
myInclude.test();

答案 2 :(得分:2)

include.js时,您必须提供require的相对路径。

如果两者都在同一目录中,请将其写为下标

var include = require('./include.js');
include.test();

include.js您可以将其定义为exports

的功能
exports.test = function(){
    console.log("log from included file");
};

更好

只导出一个具有include.js多个函数的对象,而不是导出每个单独的函数。

喜欢吼叫

include.js

exports.test = obj;
obj.func1 = function(){};
obj.func2 = function(){};

main.js

var test = require('./include.js').test;
test.func1();
test.func2();