Javascript 在 Node.js 中,如何“包含”其他文件中的函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5797852/
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
In Node.js, how do I "include" functions from my other files?
提问by TIMEX
Let's say I have a file called app.js. Pretty simple:
假设我有一个名为 app.js 的文件。很简单:
var express = require('express');
var app = express.createServer();
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.get('/', function(req, res){
res.render('index', {locals: {
title: 'NowJS + Express Example'
}});
});
app.listen(8080);
What if I have a functions inside "tools.js". How would I import them to use in apps.js?
如果我在“tools.js”中有一个函数怎么办。我将如何导入它们以在 apps.js 中使用?
Or...am I supposed to turn "tools" into a module, and then require it? << seems hard, I rather do the basic import of the tools.js file.
或者……我应该把“工具”变成一个模块,然后需要它吗?<< 看起来很难,我宁愿做 tools.js 文件的基本导入。
回答by masylum
You can require any js file, you just need to declare what you want to expose.
你可以要求任何 js 文件,你只需要声明你想要公开的内容。
// tools.js
// ========
module.exports = {
foo: function () {
// whatever
},
bar: function () {
// whatever
}
};
var zemba = function () {
}
And in your app file:
在您的应用程序文件中:
// app.js
// ======
var tools = require('./tools');
console.log(typeof tools.foo); // => 'function'
console.log(typeof tools.bar); // => 'function'
console.log(typeof tools.zemba); // => undefined
回答by Udo G
If, despite all the other answers, you still want to traditionally includea file in a node.js source file, you can use this:
如果尽管有所有其他答案,您仍然希望传统上在 node.js 源文件中包含一个文件,您可以使用以下命令:
var fs = require('fs');
// file is included here:
eval(fs.readFileSync('tools.js')+'');
- The empty string concatenation
+''
is necessary to get the file content as a string and not an object (you can also use.toString()
if you prefer). - The eval() can't be used inside a function and mustbe called inside the global scope otherwise no functions or variables will be accessible (i.e. you can't create a
include()
utility function or something like that).
- 空字符串连接
+''
对于将文件内容作为字符串而不是对象获取是必要的(.toString()
如果您愿意,也可以使用)。 - eval() 不能在函数内部使用,必须在全局范围内调用,否则将无法访问任何函数或变量(即您不能创建
include()
实用程序函数或类似的东西)。
Please note that in most cases this is bad practiceand you should instead write a module. However, there are rare situations, where pollution of your local context/namespace is what you really want.
请注意,在大多数情况下,这是不好的做法,您应该编写一个模块。但是,在极少数情况下,您真正想要的是本地上下文/命名空间的污染。
Update 2015-08-06
更新 2015-08-06
Please also note this won't work with "use strict";
(when you are in "strict mode") because functions and variables definedin the "imported" file can't be accessedby the code that does the import. Strict mode enforces some rules defined by newer versions of the language standard. This may be another reason to avoidthe solution described here.
另请注意,这不适用于"use strict";
(当您处于“严格模式”时),因为执行导入的代码无法访问“导入”文件中定义的函数和变量。严格模式强制执行由较新版本的语言标准定义的一些规则。这可能是避免此处描述的解决方案的另一个原因。
回答by Nick Panov
You need no new functions nor new modules. You simply need to execute the module you're calling if you don't want to use namespace.
您不需要新功能或新模块。如果您不想使用命名空间,您只需要执行您正在调用的模块。
in tools.js
在 tools.js 中
module.exports = function() {
this.sum = function(a,b) { return a+b };
this.multiply = function(a,b) { return a*b };
//etc
}
in app.js
在 app.js 中
or in any other .js like myController.js :
或在任何其他 .js 中,如 myController.js :
instead of
代替
var tools = require('tools.js')
which force us to use a namespace and call tools like tools.sum(1,2);
var tools = require('tools.js')
这迫使我们使用命名空间并调用类似的工具 tools.sum(1,2);
we can simply call
我们可以简单地调用
require('tools.js')();
and then
进而
sum(1,2);
in my case I have a file with controllers ctrls.js
就我而言,我有一个带有控制器ctrls.js的文件
module.exports = function() {
this.Categories = require('categories.js');
}
and I can use Categories
in every context as public class after require('ctrls.js')()
之后我可以Categories
在任何情况下作为公共课程使用require('ctrls.js')()
回答by Jayaprakash G
Create two js files
创建两个js文件
// File cal.js
module.exports = {
sum: function(a,b) {
return a+b
},
multiply: function(a,b) {
return a*b
}
};
Main js file
主js文件
// File app.js
var tools = require("./cal.js");
var value = tools.sum(10,20);
console.log("Value: "+value);
Console Output
控制台输出
Value: 30
回答by Placeholder
Here is a plain and simple explanation:
这是一个简单明了的解释:
Server.js content:
Server.js 内容:
// Include the public functions from 'helpers.js'
var helpers = require('./helpers');
// Let's assume this is the data which comes from the database or somewhere else
var databaseName = 'Walter';
var databaseSurname = 'Heisenberg';
// Use the function from 'helpers.js' in the main file, which is server.js
var fullname = helpers.concatenateNames(databaseName, databaseSurname);
Helpers.js content:
Helpers.js 内容:
// 'module.exports' is a node.JS specific feature, it does not work with regular JavaScript
module.exports =
{
// This is the function which will be called in the main file, which is server.js
// The parameters 'name' and 'surname' will be provided inside the function
// when the function is called in the main file.
// Example: concatenameNames('John,'Doe');
concatenateNames: function (name, surname)
{
var wholeName = name + " " + surname;
return wholeName;
},
sampleFunctionTwo: function ()
{
}
};
// Private variables and functions which will not be accessible outside this file
var privateFunction = function ()
{
};
回答by jmparatte
I was also looking for a NodeJS 'include' function and I checked the solution proposed by Udo G- see message https://stackoverflow.com/a/8744519/2979590. His code doesn't work with my included JS files. Finally I solved the problem like that:
我也在寻找 NodeJS 'include' 函数,我检查了Udo G提出的解决方案- 请参阅消息https://stackoverflow.com/a/8744519/2979590。他的代码不适用于我包含的 JS 文件。最后我解决了这样的问题:
var fs = require("fs");
function read(f) {
return fs.readFileSync(f).toString();
}
function include(f) {
eval.apply(global, [read(f)]);
}
include('somefile_with_some_declarations.js');
Sure, that helps.
当然,这有帮助。
回答by YouBee
create two files e.g app.js
and tools.js
创建两个文件,例如app.js
和tools.js
app.js
应用程序.js
const tools= require("./tools.js")
var x = tools.add(4,2) ;
var y = tools.subtract(4,2);
console.log(x);
console.log(y);
tools.js
工具.js
const add = function(x, y){
return x+y;
}
const subtract = function(x, y){
return x-y;
}
module.exports ={
add,subtract
}
output
输出
6
2
回答by Dharmesh
say we wants to call function ping()and add(30,20)which is in lib.jsfile from main.js
说我们要调用函数平()和添加(30,20),这是在lib.js从文件main.js
main.js
主文件
lib = require("./lib.js")
output = lib.ping();
console.log(output);
//Passing Parameters
console.log("Sum of A and B = " + lib.add(20,30))
lib.js
库.js
this.ping=function ()
{
return "Ping Success"
}
//Functions with parameters
this.add=function(a,b)
{
return a+b
}
回答by Chad Austin
The vm module in Node.js provides the ability to execute JavaScript code within the current context (including global object). See http://nodejs.org/docs/latest/api/vm.html#vm_vm_runinthiscontext_code_filename
Node.js 中的 vm 模块提供了在当前上下文(包括全局对象)中执行 JavaScript 代码的能力。见http://nodejs.org/docs/latest/api/vm.html#vm_vm_runinthiscontext_code_filename
Note that, as of today, there's a bug in the vm module that prevenst runInThisContext from doing the right when invoked from a new context. This only matters if your main program executes code within a new context and then that code calls runInThisContext. See https://github.com/joyent/node/issues/898
请注意,截至今天,vm 模块中存在一个错误,该错误阻止 runInThisContext 在从新上下文调用时执行正确的操作。这仅在您的主程序在新上下文中执行代码然后该代码调用 runInThisContext 时才重要。见https://github.com/joyent/node/issues/898
Sadly, the with(global) approach that Fernando suggested doesn't work for named functions like "function foo() {}"
遗憾的是,Fernando 建议的 with(global) 方法不适用于诸如“function foo() {}”之类的命名函数
In short, here's an include() function that works for me:
简而言之,这是一个对我有用的 include() 函数:
function include(path) {
var code = fs.readFileSync(path, 'utf-8');
vm.runInThisContext(code, path);
}
回答by Fernando
Udo G. said:
Udo G. 说:
- The eval() can't be used inside a function and must be called inside the global scope otherwise no functions or variables will be accessible (i.e. you can't create a include() utility function or something like that).
- eval() 不能在函数内部使用,必须在全局范围内调用,否则将无法访问任何函数或变量(即您不能创建 include() 实用程序函数或类似的东西)。
He's right, but there's a way to affect the global scope from a function. Improving his example:
他是对的,但有一种方法可以从函数中影响全局范围。改进他的例子:
function include(file_) {
with (global) {
eval(fs.readFileSync(file_) + '');
};
};
include('somefile_with_some_declarations.js');
// the declarations are now accessible here.
Hope, that helps.
希望,这有帮助。