gpt4 book ai didi

javascript - 即使在进行更改后,Node js 也会在控制台中显示旧文件

转载 作者:太空宇宙 更新时间:2023-11-03 23:49:45 26 4
gpt4 key购买 nike

我正在读取一个文件并使用正常工作的 fs.watch 实时查找其中的更改。现在我想在每次文件更改时调用 app.get 。但我的函数“func_read_file_lines”仍在将旧文件发送回去。我找不到问题。

const express = require('express')
const app = express()
app.set('view engine', 'ejs');
var fs = require('fs');
const request = require('request');
require('log-timestamp');
path = require("path");
var filename = path.resolve('test.txt');
const buttonPressesLogFile = filename;


fs.watch(buttonPressesLogFile, (event, filename) => {
if (filename && event === 'change') {
console.log(`${filename} file Changed`);
func_read_file_lines.
then((data) => {
let last_n_lines = data.split('\n').slice(-10, -1);
console.log(last_n_lines)
}).catch((err) => {
console.log(err)
})
}
});

let func_read_file_lines = new Promise((resolve, reject) => {
fs.readFile(filename, 'utf8', function read(err, data) {
if (err) {
console.log(err);
reject(err);
} else {
resolve(data)
}
});
})
app.get('/', (req, res) => {
func_read_file_lines.
then((data) => {
let last_n_lines = data.split('\n').slice(-10, -1);

res.render('display', {
last_n_lines: last_n_lines
});

}).catch((err) => {
console.log(err)
})
})


const port = 3000
app.listen(port, () => console.log(`Example app listening on port ${port}!`))

最佳答案

这是因为您只创建 func_read_file_lines 一次。尝试创建一个函数来返回 promise ,如下所示:

const express = require('express')
const app = express()
app.set('view engine', 'ejs');
var fs = require('fs');
const request = require('request');
require('log-timestamp');
path = require("path");
var filename = path.resolve('test.txt');
const buttonPressesLogFile = filename;


fs.watch(buttonPressesLogFile, (event, filename) => {
if (filename && event === 'change') {
console.log(`${filename} file Changed`);
func_read_file_lines.
then((data) => {
let last_n_lines = data.split('\n').slice(-10, -1);
console.log(last_n_lines)
}).catch((err) => {
console.log(err)
})
}
});

// CHANGE THE LINE BELOW
let func_read_file_lines = () => new Promise((resolve, reject) => {
fs.readFile(filename, 'utf8', function read(err, data) {
if (err) {
console.log(err);
reject(err);
} else {
resolve(data)
}
});
})
app.get('/', (req, res) => {
func_read_file_lines(). // CHANGED THIS LINE
then((data) => {
let last_n_lines = data.split('\n').slice(-10, -1);

res.render('display', {
last_n_lines: last_n_lines
});

}).catch((err) => {
console.log(err)
})
})


const port = 3000
app.listen(port, () => console.log(`Example app listening on port ${port}!`))

关于javascript - 即使在进行更改后,Node js 也会在控制台中显示旧文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59866135/

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