Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

javascript - 在Node.js中,如何从其他文件中“包含”函数?(In Node.js, how do I “include” functions from my other files?)

Let's say I have a file called app.js.

(假设我有一个名为app.js的文件。)

Pretty simple:

(很简单:)

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".

(如果我在“ tools.js”中有一个函数,该怎么办。)

How would I import them to use in apps.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文件进行基本导入。)

  ask by TIMEX translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...