是否可以在函数内导出模块?

Is it possible to export module inside a function?

所以我刚刚在 Youtube 上看了一些关于使用 Multer 上传文件的教程。

当变量 gfs 连接到我的 /routes 文件夹时,我需要导出它,但我该怎么做?

const mongoose = require("mongoose")
const Grid = require("gridfs-stream")

// Routes
const user = require("./routes/api/users")

// Init gfs
let gfs

// create gfs on connection 'open'
mongoose.connection
  .once("open", () => {
    // Init stream
    gfs = Grid(mongoose.connection.db, mongoose.mongo)
    gfs.collection("uploads")
    console.log("mongoDB connected and gfs has been created")
  })
  .on("error", err => {
    console.log("connection error", err)
  })

// I need the gfs on the user routes
// use routes
app.use("/api/users", user)
let conn = mongoose.createConnection(<url>);
let gfs = Grid(conn.db, conn.mongo);
gfs.collection("uploads");
// write routes
module.exports = gfs;

如果您想在 middleware and/or controller 中访问 gfs,您可以执行以下操作:

mongoose.connection
  .once('open', () => {
    const gfs = Grid(mongoose.connection.db, mongoose.mongo)
    gfs.collection('uploads')
    
    // use `app.locals` to store the result when it finishes
    app.locals.gfs = gfs
  })

根据 Express 文档:

The app.locals object has properties that are local variables within the application.

Once set, the value of app.locals properties persist throughout the life of the application, in contrast with res.locals properties that are valid only for the lifetime of the request.


然而,重要的是要记住,在您的 middleware and/or controller 内部,您的 route 正在处理的地方,您需要检查是否 gfs 在你使用它之前就已经存在了。

以上调用是异步的,因此 gfs 不会立即供您使用:

app.use('api/users/', user)

// routes/api/users.js
route.get('/', function(req, res, next) {
  if (req.app.locals.gfs) {
    // check if `app.locals.gfs` exists
  }
  // handle a case where `app.locals.gfs` hasn't been set yet
})

如果您想了解更多关于 app.locals 的信息,这里是 link: