我试图让下面的代码作为导出函数的中间件运行。
fs.stat("./tmp/my_data.json", (err, stats) => {
scraperDate = stats.mtime.toUTCString();
});
我有
let scraperDate = "";
在我的路线文件顶部。我试图这样做:
router.get("/", myFunctions.scraperDateFunction, function (req, res) {
res.render("my_view", {scraped: scraped, scraperDate: scraperDate});
});
当我在路线上方按原样运行 scraperDate 代码时,它可以工作。当我将它放在我的functions.js 文件到module.exports 中时,它不会写入scraperDate 变量。
我可能在这里遗漏了一些明显的东西,但我已经尝试让它在两天的大部分时间里工作。这是我的 module.exports 函数:
module.exports = {
scraperDateFunction: function(){
fs.stat("./tmp/my_data.json", (err, stats) => {
scraperDate = stats.mtime.toUTCString();
});
}
}
* 编辑 *
我现在已经试过了
getScrapeDate: function(req, res, next){
fs.stat("./tmp/my_data.json", (err, stats) => {
scraperDate = stats.mtime.toUTCString();
console.log(err)
console.log(stats)
return next;
});
}
它按预期打印 stats
控制台,没有任何错误。这可能与范围有关。我如何将结果传递 stats.mtime.toUTCString();
给路径中的 scraperDate
变量?
* 编辑 2 *
我现在在我的函数文件中有这个
getScrapeDate: function(req, res, next){
fs.stat("./tmp/my_data.json", (err, stats) => {
if (err) {
next (err);
} else {
res.locals.scraperDate = stats.mtime.toUTCString()
}
});
}
这在我的路线文件中按照建议但它不会加载我的视图
router.get("/", myFunctions.getScrapeDate, function (req, res) {
let {scraperDate} = res.locals;
res.render("my_view", {scraped: scraped, scraperDate:
scraperDate});
});
scraped 在路由文件的顶部声明。
*最终编辑*
这是一个正在运行的设置
router.get("/", myFunctions.getScrapeDate, function (req, res) {
let {scraperDate} = res.locals;
res.render("my_view", {scraped, scraperDate});
});
和
getScrapeDate: function(req, res, next){
fs.stat("./tmp/my_data.json", (err, stats) => {
if (err) {
next (err);
} else {
res.locals.scraperDate = stats.mtime.toUTCString();
next();
}
});
}