gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:09:19 25 4
gpt4 key购买 nike

所以我刚刚在 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)

最佳答案

如果您想访问中间件和/或 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.

<小时/>

但是,请务必记住,在处理路由中间件和/或 Controller 内部,您在对 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 的更多信息,请点击以下链接:

关于javascript - 是否可以在函数内导出模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57448936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com