繁体   English   中英

Node.js基础知识:如何以及在何处可以使用require(module)?

[英]Nodejs basics: How and where I can use require(module)?

我刚刚开始玩nodeJs。 目前,我有这样的项目:

结构:-app.js-response.js

app.js代码:

var callback = require('./response.js');
var express = require('express');
var bodyParser = require('body-parser');

var app = express();
var port = process.env.PORT || 3000;

// body parser middleware
app.use(bodyParser.urlencoded({ extended: true }));

// test route
app.get('/', function (req, res) { res.status(200).send('Hello world!') });

app.post('/test', callback);

// error handler
app.use(function (err, req, res, next) {
  console.error(err.stack);
  res.status(400).send(err.message);
});

app.listen(port, function () {
  console.log('Slack bot listening on port ' + port);
});

我的response.js是:

module.exports = function (req, res, next) {
  return res.status(200).json({
    attachments: [{ "test": "test" }})]
  });
}

如您所见,我正在使用Express Server侦听对/ test端点的发布请求,并使用一些测试json进行响应。

问题:我想使用mongo-从数据库中获取相同的数据,并在触发/ test端点时返回响应。 Mongodb教程指导我安装mongodb npm模块,然后包括mongodb模块,并像下面这样做其余的工作:

// Retrieve
var MongoClient = require('mongodb').MongoClient;

// Connect to the db
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
  if(!err) {
    console.log("We are connected");
  }
});
  • 我可以在response.js中要求使用mongodb(require('mongodb'))吗? 如果是,它应该在函数内部还是在module.exports外部?
  • 如果我在app.js中需要('mongodb'),是否可以在response.js中使用它?

您可以在每个模块中要求任何内容。 使用要求仅在所有范围之外使用(不起作用),因为它是同步方法,并且会阻塞您的服务器。 同样可以在多个其他模块中需要相同的模块。 节点js知道不重新编译它。

希望对您有所帮助。

是的,您可以在response.js中要求mongodb,它应该在导出文件之外。 如果您需要在app.js中使用mongodb,则将无法在response.js中使用它

暂无
暂无

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

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