繁体   English   中英

在 Node.js 中,如何从我的其他文件中“包含”函数?

[英]In Node.js, how do I "include" functions from my other files?

假设我有一个名为 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);

如果我在“tools.js”中有一个函数怎么办? 我将如何导入它们以在 apps.js 中使用?

或者......我应该把“工具”变成一个模块,然后需要它吗? << 看起来很难,我宁愿做 tools.js 文件的基本导入。

你可以要求任何 js 文件,你只需要声明你想要公开的内容。

// tools.js
// ========
module.exports = {
  foo: function () {
    // whatever
  },
  bar: function () {
    // whatever
  }
};

var zemba = function () {
}

在您的应用程序文件中:

// app.js
// ======
var tools = require('./tools');
console.log(typeof tools.foo); // => 'function'
console.log(typeof tools.bar); // => 'function'
console.log(typeof tools.zemba); // => undefined

如果尽管有所有其他答案,您仍然希望传统上在 node.js 源文件中包含一个文件,您可以使用以下命令:

var fs = require('fs');

// file is included here:
eval(fs.readFileSync('tools.js')+'');
  • 空字符串连接+''是获取文件内容作为字符串而不是对象所必需的.toString()如果您愿意,也可以使用.toString() )。
  • eval() 不能在函数内部使用,必须在全局范围内调用,否则将无法访问任何函数或变量(即您不能创建include()实用程序函数或类似的东西)。

请注意,在大多数情况下,这是不好的做法,您应该编写一个模块 但是,在极少数情况下,您真正​​想要的是本地上下文/命名空间的污染。

更新 2015-08-06

另请注意,这不适用于"use strict"; (当您处于“严格模式”时),因为执行导入的代码无法访问“导入”文件中定义的函数和变量。 严格模式强制执行由较新版本的语言标准定义的一些规则。 这可能是避免此处描述的解决方案的另一个原因。

您不需要新功能或新模块。 如果您不想使用命名空间,您只需要执行您正在调用的模块。

在 tools.js 中

module.exports = function() { 
    this.sum = function(a,b) { return a+b };
    this.multiply = function(a,b) { return a*b };
    //etc
}

在 app.js 中

或在任何其他 .js 中,如 myController.js :

代替

var tools = require('tools.js')这迫使我们使用命名空间并调用tools.sum(1,2);类的工具tools.sum(1,2);

我们可以简单地调用

require('tools.js')();

进而

sum(1,2);

就我而言,我有一个带有控制器ctrls.js的文件

module.exports = function() {
    this.Categories = require('categories.js');
}

require('ctrls.js')()之后,我可以在每个上下文中使用Categories作为公共类

创建两个js文件

// File cal.js
module.exports = {
    sum: function(a,b) {
        return a+b
    },
    multiply: function(a,b) {
        return a*b
    }
};

主js文件

// File app.js
var tools = require("./cal.js");
var value = tools.sum(10,20);
console.log("Value: "+value);

控制台输出

Value: 30

创建两个文件,例如app.jstools.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);

工具.js

 const add = function(x, y){
        return x+y;
    }
 const subtract = function(x, y){
            return x-y;
    }
    
    module.exports ={
        add,subtract
    }

输出

6
2

这是一个简单明了的解释:

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 内容:

// '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 () 
{
};

我也在寻找 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');

当然,这有帮助。

创建两个 JavaScript 文件。 例如import_functions.jsmain.js

1.) import_functions.js

// Declaration --------------------------------------

 module.exports =
   {
     add,
     subtract
     // ...
   }


// Implementation ----------------------------------

 function add(x, y)
 {
   return x + y;
 }

 function subtract(x, y)
 {
   return x - y;
 }
    

// ...

2.) main.js

// include ---------------------------------------

const sf= require("./import_functions.js")

// use -------------------------------------------

var x = sf.add(4,2);
console.log(x);

var y = sf.subtract(4,2);
console.log(y);

    

输出

6
2

Node.js 中的 vm 模块提供了在当前上下文(包括全局对象)中执行 JavaScript 代码的能力。 http://nodejs.org/docs/latest/api/vm.html#vm_vm_runinthiscontext_code_filename

请注意,截至今天,vm 模块中存在一个错误,该错误阻止 runInThisContext 在从新上下文调用时执行正确的操作。 这仅在您的主程序在新上下文中执行代码然后该代码调用 runInThisContext 时才重要。 https://github.com/joyent/node/issues/898

遗憾的是,Fernando 建议的 with(global) 方法不适用于诸如“function foo() {}”之类的命名函数

简而言之,这是一个对我有用的 include() 函数:

function include(path) {
    var code = fs.readFileSync(path, 'utf-8');
    vm.runInThisContext(code, path);
}

假设我们想从main.js 调用lib.js文件中的函数ping()add(30,20)

主文件

lib = require("./lib.js")

output = lib.ping();
console.log(output);

//Passing Parameters
console.log("Sum of A and B = " + lib.add(20,30))

库.js

this.ping=function ()
{
    return  "Ping Success"
}
//Functions with parameters
this.add=function(a,b)
    {
        return a+b
    }

Udo G. 说:

  • eval() 不能在函数内部使用,必须在全局范围内调用,否则将无法访问任何函数或变量(即您不能创建 include() 实用程序函数或类似的东西)。

他是对的,但是有一种方法可以从函数中影响全局范围。 改进他的例子:

function include(file_) {
    with (global) {
        eval(fs.readFileSync(file_) + '');
    };
};

include('somefile_with_some_declarations.js');

// the declarations are now accessible here.

希望,这有帮助。

它与我一起工作,如下所示......

Lib1.js

//Any other private code here 

// Code you want to export
exports.function1 = function(params) {.......};
exports.function2 = function(params) {.......};

// Again any private code

现在在Main.js文件中,您需要包含Lib1.js

var mylib = requires('lib1.js');
mylib.function1(params);
mylib.function2(params);

请记住将 Lib1.js 放在node_modules 文件夹中

在我看来,另一种方法是在调用require()函数时执行 lib 文件中的所有内容(function(/* things here */){})(); 这样做将使所有这些函数成为全局范围,就像eval()解决方案一样

源代码/库.js

(function () {
    funcOne = function() {
            console.log('mlt funcOne here');
    }

    funcThree = function(firstName) {
            console.log(firstName, 'calls funcThree here');
    }

    name = "Mulatinho";
    myobject = {
            title: 'Node.JS is cool',
            funcFour: function() {
                    return console.log('internal funcFour() called here');
            }
    }
})();

然后在您的主代码中,您可以按名称调用您的函数,例如:

主文件

require('./src/lib')
funcOne();
funcThree('Alex');
console.log(name);
console.log(myobject);
console.log(myobject.funcFour());

将使这个输出

bash-3.2$ node -v
v7.2.1
bash-3.2$ node main.js 
mlt funcOne here
Alex calls funcThree here
Mulatinho
{ title: 'Node.JS is cool', funcFour: [Function: funcFour] }
internal funcFour() called here
undefined

当你调用我的object.funcFour()时注意undefined ,如果你用eval()加载它也会一样。 希望能帮助到你 :)

应用程序.js

let { func_name } = require('path_to_tools.js');
func_name();    //function calling

工具.js

let func_name = function() {
    ...
    //function body
    ...
};

module.exports = { func_name };

我只想补充一点,如果您只需要从tools.js导入某些函数,那么您可以使用自6.4版起在 node.js 中支持的解构赋值- 请参阅node.green


示例:(两个文件都在同一个文件夹中)

工具.js

module.exports = {
    sum: function(a,b) {
        return a + b;
    },
    isEven: function(a) {
        return a % 2 == 0;
    }
};

主文件

const { isEven } = require('./tools.js');

console.log(isEven(10));

输出: true


这也避免了您将这些函数分配为另一个对象的属性,就像在以下(常见)分配中的情况一样:

const tools = require('./tools.js');

你需要在那里调用tools.isEven(10)


笔记:

不要忘记使用正确的路径作为文件名的前缀 - 即使两个文件都在同一个文件夹中,您也需要使用./

来自Node.js 文档

如果没有前导 '/'、'./' 或 '../' 来指示文件,则该模块必须是核心模块或从 node_modules 文件夹加载。

您可以将您的函数放在全局变量中,但更好的做法是将您的工具脚本变成一个模块。 这真的不是太难 - 只需将您的公共 API 附加到exports对象。 查看了解 Node.js 的导出模块以获取更多详细信息。

包含文件并在给定(非全局)上下文中运行它

fileToInclude.js

define({
    "data": "XYZ"
});

主文件

var fs = require("fs");
var vm = require("vm");

function include(path, context) {
    var code = fs.readFileSync(path, 'utf-8');
    vm.runInContext(code, vm.createContext(context));
}


// Include file

var customContext = {
    "define": function (data) {
        console.log(data);
    }
};
include('./fileToInclude.js', customContext);

使用 ESM 模块系统:

a.js

export default function foo() {};

export function bar() {};

b.js

import foo, {bar} from './a.js';

这是我迄今为止创建的最佳方式。

var fs = require('fs'),
    includedFiles_ = {};

global.include = function (fileName) {
  var sys = require('sys');
  sys.puts('Loading file: ' + fileName);
  var ev = require(fileName);
  for (var prop in ev) {
    global[prop] = ev[prop];
  }
  includedFiles_[fileName] = true;
};

global.includeOnce = function (fileName) {
  if (!includedFiles_[fileName]) {
    include(fileName);
  }
};

global.includeFolderOnce = function (folder) {
  var file, fileName,
      sys = require('sys'),
      files = fs.readdirSync(folder);

  var getFileName = function(str) {
        var splited = str.split('.');
        splited.pop();
        return splited.join('.');
      },
      getExtension = function(str) {
        var splited = str.split('.');
        return splited[splited.length - 1];
      };

  for (var i = 0; i < files.length; i++) {
    file = files[i];
    if (getExtension(file) === 'js') {
      fileName = getFileName(file);
      try {
        includeOnce(folder + '/' + file);
      } catch (err) {
        // if (ext.vars) {
        //   console.log(ext.vars.dump(err));
        // } else {
        sys.puts(err);
        // }
      }
    }
  }
};

includeFolderOnce('./extensions');
includeOnce('./bin/Lara.js');

var lara = new Lara();

您仍然需要告知您要导出的内容

includeOnce('./bin/WebServer.js');

function Lara() {
  this.webServer = new WebServer();
  this.webServer.start();
}

Lara.prototype.webServer = null;

module.exports.Lara = Lara;

我想出了一种相当粗糙的方法来处理HTML模板。 类似于PHP <?php include("navigation.html"); ?> <?php include("navigation.html"); ?>

server.js

var fs = require('fs');

String.prototype.filter = function(search,replace){
    var regex = new RegExp("{{" + search.toUpperCase() + "}}","ig");
    return this.replace(regex,replace);
}

var navigation = fs.readFileSync(__dirname + "/parts/navigation.html");

function preProcessPage(html){
    return html.filter("nav",navigation);
}

var express = require('express');
var app = express();
// Keep your server directory safe.
app.use(express.static(__dirname + '/public/'));
// Sorta a server-side .htaccess call I suppose.
app.get("/page_name/",function(req,res){
    var html = fs.readFileSync(__dirname + "/pages/page_name.html");
    res.send(preProcessPage(html));
});

page_name.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>NodeJS Templated Page</title>
    <link rel="stylesheet" type="text/css" href="/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="/css/font-awesome.min.css">
    <!-- Scripts Load After Page -->
    <script type="text/javascript" src="/js/jquery.min.js"></script>
    <script type="text/javascript" src="/js/tether.min.js"></script>
    <script type="text/javascript" src="/js/bootstrap.min.js"></script>
</head>
<body>
    {{NAV}}
    <!-- Page Specific Content Below Here-->
</body>
</html>

navigation.html

<nav></nav>

载入页面结果

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>NodeJS Templated Page</title>
    <link rel="stylesheet" type="text/css" href="/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="/css/font-awesome.min.css">
    <!-- Scripts Load After Page -->
    <script type="text/javascript" src="/js/jquery.min.js"></script>
    <script type="text/javascript" src="/js/tether.min.js"></script>
    <script type="text/javascript" src="/js/bootstrap.min.js"></script>
</head>
<body>
    <nav></nav>
    <!-- Page Specific Content Below Here-->
</body>
</html>

Node 基于 commonjs 模块和最近的 esm 模块工作。 基本上,您应该在 separated.js 文件中创建模块并使用导入/导出(module.exports 和 require)。

Javascript 在浏览器上的工作方式不同,基于 scope。有全局 scope,通过 clojures(其他函数中的函数)你有私有范围。

因此,在节点中,导出您将在其他模块中使用的函数和对象。

IMO 最干净的方法如下,在 tools.js 中:

function A(){
.
.
.
}

function B(){
.
.
.
}

module.exports = {
A,
B
}

然后,在 app.js 中,只需要 tools.js 如下: const tools = require("tools");

我也在寻找一个选项来包含代码而不编写模块,resp。 对 Node.js 服务使用来自不同项目的相同经过测试的独立源代码 - jmparatte的回答为我做到了。

好处是,你不会污染命名空间,我没有"use strict";麻烦"use strict"; 它运作良好。

这是一个完整的示例:

要加载的脚本 - /lib/foo.js

"use strict";

(function(){

    var Foo = function(e){
        this.foo = e;
    }

    Foo.prototype.x = 1;

    return Foo;

}())

示例模块 - index.js

"use strict";

const fs = require('fs');
const path = require('path');

var SampleModule = module.exports = {

    instAFoo: function(){
        var Foo = eval.apply(
            this, [fs.readFileSync(path.join(__dirname, '/lib/foo.js')).toString()]
        );
        var instance = new Foo('bar');
        console.log(instance.foo); // 'bar'
        console.log(instance.x); // '1'
    }

}

希望这在某种程度上有所帮助。

就像你有一个文件abc.txt等等?

创建 2 个文件: fileread.jsfetchingfile.js ,然后在fileread.js编写以下代码:

function fileread(filename) {
    var contents= fs.readFileSync(filename);
        return contents;
    }

    var fs = require("fs");  // file system

    //var data = fileread("abc.txt");
    module.exports.fileread = fileread;
    //data.say();
    //console.log(data.toString());
}

fetchingfile.js编写以下代码:

function myerror(){
    console.log("Hey need some help");
    console.log("type file=abc.txt");
}

var ags = require("minimist")(process.argv.slice(2), { string: "file" });
if(ags.help || !ags.file) {
    myerror();
    process.exit(1);
}
var hello = require("./fileread.js");
var data = hello.fileread(ags.file);  // importing module here 
console.log(data.toString());

现在,在终端中: $ node fetchingfile.js --file=abc.txt

您将文件名作为参数传递,而且在readfile.js包含所有文件而不是传递它。

谢谢

使用 node.js 和 express.js 框架时的另一种方法

var f1 = function(){
   console.log("f1");
}
var f2 = function(){
   console.log("f2");
}

module.exports = {
   f1 : f1,
   f2 : f2
}

将其存储在名为 s 的 js 文件和文件夹 statics 中

现在使用该功能

var s = require('../statics/s');
s.f1();
s.f2();

您可以简单地使用require('./filename')

例如。

// file: index.js
var express = require('express');
var app = express();
var child = require('./child');
app.use('/child', child);
app.get('/', function (req, res) {
  res.send('parent');
});
app.listen(process.env.PORT, function () {
  console.log('Example app listening on port '+process.env.PORT+'!');
});
// file: child.js
var express = require('express'),
child = express.Router();
console.log('child');
child.get('/child', function(req, res){
  res.send('Child2');
});
child.get('/', function(req, res){
  res.send('Child');
});

module.exports = child;

请注意:

  1. 您不能在子文件上侦听 PORT,只有父 Express 模块具有 PORT 侦听器
  2. 孩子正在使用“路由器”,而不是父 Express 模块。

如果您想利用多个CPU和微服务体系结构来加快处理速度,请在分叉进程上使用RPC。

听起来很复杂,但是使用章鱼很简单。

这是一个例子:

在tools.js上添加:

const octopus = require('octopus');
var rpc = new octopus('tools:tool1');

rpc.over(process, 'processRemote');

var sum = rpc.command('sum'); // This is the example tool.js function to make available in app.js

sum.provide(function (data) { // This is the function body
    return data.a + data.b;
});

在app.js上,添加:

const { fork } = require('child_process');
const octopus = require('octopus');
const toolprocess = fork('tools.js');

var rpc = new octopus('parent:parent1');
rpc.over(toolprocess, 'processRemote');

var sum = rpc.command('sum');

// Calling the tool.js sum function from app.js
sum.call('tools:*', {
    a:2, 
    b:3
})
.then((res)=>console.log('response : ',rpc.parseResponses(res)[0].response));

披露-我是章鱼的作者,并且为我的类似用例而构建,因为我找不到任何轻量级的库。

把“工具”变成一个模块,我觉得一点也不难。 尽管有所有其他答案,我仍然建议使用 module.exports:

//util.js
module.exports = {
   myFunction: function () {
   // your logic in here
   let message = "I am message from myFunction";
   return message; 
  }
}

现在我们需要将此导出分配给全局范围(在您的 app|index|server.js 中)

var util = require('./util');

现在您可以将函数引用和调用为:

//util.myFunction();
console.log(util.myFunction()); // prints in console :I am message from myFunction 

要在 Unix 环境中以交互方式测试模块./test.js ,可以使用这样的方法:

    >> node -e "eval(''+require('fs').readFileSync('./test.js'))" -i
    ...

用:

var mymodule = require("./tools.js")

应用程序.js:

module.exports.<your function> = function () {
    <what should the function do>
}

暂无
暂无

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

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