在 node.js 中包含一个 .js 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7310176/
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
Including a .js file in node.js
提问by Tom
I am trying to include this script in my app: http://www.movable-type.co.uk/scripts/latlong.html
我正在尝试将此脚本包含在我的应用程序中:http: //www.movable-type.co.uk/scripts/latlong.html
I have saved it in a file called lib/latlon.js, and I am trying to include it like this:
我已经将它保存在一个名为 lib/latlon.js 的文件中,我试图像这样包含它:
require('./lib/latlon.js');
How should I go about including a JS library like this?
我应该如何去包含这样的 JS 库?
回答by J?rgen
First of all, you should take a look at the Modules documentation for node.js: http://nodejs.org/docs/v0.5.5/api/modules.html
首先,您应该查看 node.js 的模块文档:http: //nodejs.org/docs/v0.5.5/api/modules.html
The script you're trying to include is not a node.js module, so you should make a few changes to it. As there is no shared global scope between the modules in node.js you need to add all the methods you want to access to the exports object. If you add this line to your latlon.js file:
您尝试包含的脚本不是 node.js 模块,因此您应该对其进行一些更改。由于 node.js 中的模块之间没有共享的全局范围,因此您需要将所有要访问的方法添加到导出对象中。如果将此行添加到 latlon.js 文件中:
exports.LatLon = LatLon;
...you should be able to access the LatLon function like this:
...您应该能够像这样访问 LatLon 函数:
var LatLonModule = require('./lib/latlon.js');
var latlongObj = new LatLonModule.LatLon(lat, lon, rad);

