简体   繁体   English

在node.js上添加外部javascript文件

[英]Adding external javascript files on node.js

I have a node server and I want to add an external .js file (say something.js ). 我有一个节点服务器,我想添加一个外部.js文件(比如something.js )。 I have this code for now: 我现在有这个代码:

var st = require('./js/something');

Where something.js is the JavaScript file inside a /js/ folder. 其中something.js/js/文件夹中的JavaScript文件。 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定义的函数时,节点告诉我它们没有定义。

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() . 我也尝试使用像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. logging 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");
}

Node.js uses the CommonJS module format. Node.js使用CommonJS模块格式。 Essentially values that are attached to the exports object are available to users of the module. 本质上,附加到exports对象的值可供模块用户使用。 So if you are using a module like this 所以如果你使用这样的模块

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对象。

exports.s = function () {
    console.log("s");
}

exports.t = function () {
    console.log("t");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM