I was reading around on Stack Overflow/Google and saw a method of including a js file for use of its contents in another file..
我在Stack Overflow / Google上阅读并看到了一种方法,包括一个js文件,用于在另一个文件中使用它的内容。
I have admin.js and index.js, in admin.js I need to access an array in index.js.
我有admin.js和index.js,在admin.js我需要访问index.js中的数组。
In index.js I have:
在index.js我有:
exports.chatrooms = function(){
return usernames;
}
In admin.js I have:
在admin.js我有:
var indexFileInclude = require('index.js');
var chatrooms = indexFileInclude.chatrooms();
console.log(JSON.stringify(chatrooms));
I get an error:
我收到一个错误:
Missing error handler on `socket`.
Error: Cannot find module 'index.js'
What am I doing wrong
我究竟做错了什么
1 个解决方案
#1
3
With require()
if you do not specify a path it will assume you're targeting the node_modules folder. To instead pull a module in the same folder, you would use the ./
notation to specify you want to target the current folder.
使用require()如果您没有指定路径,它将假定您的目标是node_modules文件夹。要将模块拉入同一文件夹,您可以使用./表示法指定要定位当前文件夹。
var indexFileInclude = require('./index');
#1
3
With require()
if you do not specify a path it will assume you're targeting the node_modules folder. To instead pull a module in the same folder, you would use the ./
notation to specify you want to target the current folder.
使用require()如果您没有指定路径,它将假定您的目标是node_modules文件夹。要将模块拉入同一文件夹,您可以使用./表示法指定要定位当前文件夹。
var indexFileInclude = require('./index');