我为自己编写了一个node.js小型应用程序,该应用程序使用小型js代码清除了处理请求之前的缓存:
let clearCache
if (process.env.NODE_ENV === 'development') {
const {cache} = require
clearCache = (except) => {
for (let key in cache)
if (!except.includes(key) && key.indexOf('/node_modules/') === -1)
delete cache[key]
}
} else {
clearCache = () => {}
}
const { createServer } = require('http')
const persistentPaths = ['/path/to/my/db/file']
createServer((req, res) => {
clearCache(persistentPaths)
require('./handleRequest')(req, res)
}).listen(3000, () => {})
我相信这是在开发中使用应用程序的最有效方法。
当我更改代码时,它立即生效,对我来说很好用。
现在,我想使用express.js,似乎无法使用这种方法。
好吧,看来这是一个自我解答的问题,我需要使用nodemon。
但是我真的不想使用将监视所有文件并重新启动整个服务器的工具。恐怕会慢很多。
在我的示例中,您可以看到我重新加载了除db文件之外的文件,因此开发中的我的应用程序仅与数据库连接一次并保持该连接。如果使用nodemon应用程序时还需要加载所有node_modules代码,则每次更改代码后都要与db建立新的连接,也许它将每次都连接到postgres和redis。
问题是:我不能以这种方式这样做,是否有解决方案来为express.js重新加载模块?
做到了!如果您能分享自己的想法,将非常高兴。
因为我只能用Google搜索nodemon和chokidar解决方案,也许我做的事情很奇怪,所以这是我的解决方案:
server.ts:
import express from 'express'
const app = express()
const port = 3000
app.listen(port, () =>
console.log(`Example app listening at http://localhost:${port}`)
)
if (process.env.NODE_ENV === 'development') {
const {cache} = require
const persistentFiles: string[] = []
const clearCache = (except: string[]) => {
for (let key in cache)
if (!except.includes(key) && key.indexOf('/node_modules/') === -1)
delete cache[key]
}
app.use((req, res, next) => {
clearCache(persistentFiles)
const {router} = require('config/routes')
router.handle(req, res, next)
})
} else {
const router = require('config/routes')
app.use(router.handle)
}
和routes.ts:
import {Router, Request, Response} from 'express'
export const router = Router()
router.get('/', function (req: Request, res: Response) {
res.send('Hello world')
})
用法:NODE_ENV =开发NODE_PATH = src节点src / server.js
((我的IDE在编辑时将ts编译为js并放在此处,如果您使用的是VS代码,我想它可能会更复杂)
您无需编写一个实用程序。您可以使用类似chokidar的模块。您可以指定目录,并忽略同一时间。
您可以在回调时重新加载手表。
[示例维基]:> [https://github.com/paulmillr/chokidar
const chokidar = require("chokidar");
// Full list of options. See below for descriptions.
// Do not use this example!
chokidar.watch("file", {
persistent: true,
ignored: "*.txt",
ignoreInitial: false,
followSymlinks: true,
cwd: ".",
disableGlobbing: false,
awaitWriteFinish: {
stabilityThreshold: 2000,
pollInterval: 100,
},
ignorePermissionErrors: false,
atomic: true, // or a custom 'atomicity delay', in milliseconds (default 100)
});
// One-liner for current directory
chokidar.watch(".").on("all", (event, path) => {
// Reload module here.
});