include.js
file contain
var test = function(){
console.log("log from included file");
};
main.js
file contain
require('./include.js');
test();
when i tried to run main.js
using node main.js
command it shows
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)
what is the reason for this error ?
You will need to export the test function in order to use it in main.js
var test = function(){
console.log("log from included file");
};
module.exports = test
And in main.js
add require
as follows
require('./include.js'); // assuming include.js is in same directory as main.js
If you do require('include.js')
then node will search include
in global packages
The error refers to a file not being found, make sure your file is in the same directory as main.js and try:
include.js
module.exports = {
test: function(){
console.log("log from included file");
}
}
main.js
var myInclude = require('include.js');
myInclude.test();
You will have to give relative path of include.js
while require
.
If both are in same directory write it like bellow
var include = require('./include.js');
include.test();
and from include.js
you can define them as function for exports
exports.test = function(){
console.log("log from included file");
};
Even Better
export just one object having multiple functions from include.js
instead of exporting each separate function.
Like bellow
include.js
exports.test = obj;
obj.func1 = function(){};
obj.func2 = function(){};
main.js
var test = require('./include.js').test;
test.func1();
test.func2();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.