我創建了一個helper.js包含helper functions. 為了使用輔助函式,我必須在我希望使用它的所有位置匯入檔案。有沒有什么辦法可以load/import將helper.js檔案globally?
helper.js
module.exports = {
responseObject: function (status, message, data, error) {
return {
status: status,
message: message,
data: data,
error: error
}
}
}
索引.js
// load mongoose
require('./db/mongoose')
const express = require('express')
const app = express()
const port = process.env.PORT || 3000
app.use(helper)
// load routers
const userRouter = require('./routers/user')
app.use(express.json()) // automatically converts incoming requests to json
app.use(userRouter)
app.listen(port)
用戶控制器.js
const User = require("../models/user")
const helper = require("../helper")
exports.createUser = async (req, res) => {
const user = new User(req.body)
try {
await user.save()
res.status(201).send({
status: true,
message: 'Registration success',
data: user,
error: {}
})
} catch (error) {
const response = helper.responseObject(false, "Wrong", {}, error)
res.status(400).send(response);
}
}
uj5u.com熱心網友回復:
從檔案:
在瀏覽器中,頂級作用域是全域作用域。這意味著在瀏覽器 var 中將定義一個新的全域變數。在 Node.js 中這是不同的。頂級作用域不是全域作用域;Node.js 模塊中的 var 某些內容將是該模塊的本地內容。
這意味著您不能只responseObject在“全域”范圍內定義您的范圍,因為它總是指模塊的本地范圍,并且不適用于其他模塊。
但是有一種方法可以做到這一點,盡管我不推薦它(搜索 Google 或SO為什么會這樣,這已經詳細討論過了)。您可以將您function/variable的添加到global物件中(有點類似于window瀏覽器中的關鍵字):
// in your app.js "add" the exported stuff from the helper-module to the global object
const express = require('express')
...
global.myHelper = require('./helper');
// in e.g. your user-controller you could then access it like
const response = global.myHelper.responseObject(false, "Wrong", {}, error)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/398158.html
標籤:节点.js
