在 node.js 上添加外部 javascript 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8508383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding external javascript files on node.js
提问by Masiar
I have a node server and I want to add an external .js file (say something.js
). I have this code for now:
我有一个节点服务器,我想添加一个外部 .js 文件(比如something.js
)。我现在有这个代码:
var st = require('./js/something');
var st = require('./js/something');
Where something.js
is the JavaScript file inside a /js/
folder. The server compiles and run, but when I try to use functions defined in something.js
node tells me they are not defined.
something.js
文件/js/
夹中的 JavaScript 文件在哪里。服务器编译并运行,但是当我尝试使用something.js
node 中定义的函数时,告诉我它们没有定义。
I also tried to run them using like st.s()
but nothing happens and I have an error saying that the object has no method s()
.
我也尝试使用 like 运行它们,st.s()
但没有任何反应,我有一个错误,说该对象没有方法s()
。
Can anyone help me?
谁能帮我?
Thanks,
谢谢,
EDIT:
编辑:
logging st
gives {}
(I obtain it from console.log(JSON.stringify(st))
. Also doing console.log(st)
gives {}
as result.
日志记录st
给出{}
(我从 获得它console.log(JSON.stringify(st))
。也做console.log(st)
给出{}
了结果。
The content of something.js
is just a bunch of functions defined like this
的内容something.js
只是一堆这样定义的函数
function s() {
alert("s");
}
function t() {
alert("t");
}
回答by DHamrick
Node.js uses the CommonJSmodule format. Essentially values that are attached to the exports
object are available to users of the module. So if you are using a module like this
Node.js 使用CommonJS模块格式。本质上,附加到exports
对象的值可供模块用户使用。所以如果你使用这样的模块
var st = require('./js/something');
st.s();
st.t();
Your module has to export those functions. So you need to attach them to the exports object.
您的模块必须导出这些函数。因此,您需要将它们附加到导出对象。
exports.s = function () {
console.log("s");
}
exports.t = function () {
console.log("t");
}