Javascript 在 node.js 应用程序中包含外部 .js 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5625569/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:07:57  来源:igfitidea点击:

include external .js file in node.js app

javascriptnode.js

提问by Luc

I have an app.js node application. As this file is starting to grow, I would like to move some part of the code in some other files that I would "require" or "include" in the app.js file.

我有一个 app.js 节点应用程序。随着此文件开始增长,我想将部分代码移动到我将在 app.js 文件中“要求”或“包含”的其他一些文件中。

I'm trying things like:

我正在尝试这样的事情:

// Declare application
var app = require('express').createServer();

// Declare usefull stuff for DB purposes
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

// THE FOLLOWING REQUIRE DOES NOT WORK
require('./models/car.js');

in car.js:

在 car.js 中:

// Define Car model
CarSchema = new Schema({
  brand        : String,
  type : String
});
mongoose.model('Car', CarSchema);

I got the error:

我得到了错误:

ReferenceError: Schema is not defined

I'm just looking to have the content of car.js loaded (instead of having everything in the same app.js file) Is there a particuliar way to do this in node.js ?

我只是想加载 car.js 的内容(而不是将所有内容都放在同一个 app.js 文件中)在 node.js 中有没有一种特殊的方法可以做到这一点?

回答by Raynos

To place an emphasis on what everyone else has been saying var fooin top level does not create a global variable. If you want a global variable then write global.foo. but we allknow globals are evil.

将重点放在其他人var foo在顶层所说的内容上并不会创建全局变量。如果你想要一个全局变量,那么写global.foo. 但我们知道全局变量是邪恶的。

If you are someone who uses globals like that in a node.js project I was on I would refactor them away for as there are just so few use cases for this (There are a few exceptions but this isn't one).

如果您是在我参与的 node.js 项目中使用这样的全局变量的人,我会重构它们,因为这样的用例很少(有一些例外,但这不是一个)。

// Declare application
var app = require('express').createServer();

// Declare usefull stuff for DB purposes
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

require('./models/car.js').make(Schema, mongoose);

in car.js

在 car.js 中

function make(Schema, mongoose) {
    // Define Car model
    CarSchema = new Schema({
      brand        : String,
      type : String
    });
    mongoose.model('Car', CarSchema);
}

module.exports.make = make;

回答by kybernetikos

The correct answer is usually to use require, but in a few cases it's not possible.

正确的答案通常是使用 require,但在少数情况下是不可能的。

The following code will do the trick, but use it with care:

以下代码可以解决问题,但请谨慎使用:

var fs = require('fs');
var vm = require('vm');
var includeInThisContext = function(path) {
    var code = fs.readFileSync(path);
    vm.runInThisContext(code, path);
}.bind(this);
includeInThisContext(__dirname+"/models/car.js");

回答by Dorian

Short answer:

简短的回答:

// lib.js
module.exports.your_function = function () {
  // Something...
};

// app.js
require('./lib.js').your_function();

回答by Stephen

you can put

你可以放

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

at the top of your car.js file for it to work, or you can do what Raynos said to do.

在你的 car.js 文件的顶部让它工作,或者你可以按照 Raynos 说的去做。

回答by Bouke Versteegh

If you just want to test a library from the command line, you could do:

如果您只想从命令行测试库,您可以执行以下操作:

cat somelibrary.js mytestfile.js | node

回答by Marcio Pamplona

This approach works for me in Node.js, Is there any problem with this one?

这种方法在 Node.js 中对我有用,这个方法有什么问题吗?

File 'include.js':

文件'include.js':

fs = require('fs');

File 'main.js':

文件“main.js”:

require('./include.js');

fs.readFile('./file.json', function (err, data) {
    if (err) {
        console.log('ERROR: file.json not found...')
    } else {
        contents = JSON.parse(data)
    };
})