在node.js上添加外部javascript文件 [英] Adding external javascript files on node.js

查看:65
本文介绍了在node.js上添加外部javascript文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个节点服务器,我想添加一个外部.js文件(比如 something.js )。我现在有这个代码:

I have a node server and I want to add an external .js file (say something.js). I have this code for now:

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

其中 something.js / js / 文件夹。服务器编译并运行,但是当我尝试使用中定义的函数时,something.js 节点告诉我它们没有被定义。

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.

我也尝试使用类似 st.s()运行它们,但没有任何反应,我有一个错误,说该对象没有方法 s()

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().

任何人都可以帮助我吗?

Can anyone help me?

谢谢,

编辑:

记录 st 给出 {} (我是从 console.log(JSON.stringify(st))获得的。还要做 console.log(st)结果为 {}

logging st gives {} (I obtain it from console.log(JSON.stringify(st)). Also doing console.log(st) gives {} as result.

something.js 只是一堆像这样定义的函数

The content of something.js is just a bunch of functions defined like this

function s() {
    alert("s");
}

function t() {
    alert("t");
}


推荐答案

Node.js使用CommonJS 模块格式.Essentia附加到 exports 对象的lly值可供模块用户使用。所以如果你使用这样的模块

Node.js uses the CommonJS module 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

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

您的模块必须导出这些功能。所以你需要将它们附加到exports对象。

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");
}

这篇关于在node.js上添加外部javascript文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆