javascript - 编辑文件并在nodejs中再次读取编辑后的文件
问题描述
我有一个包含大约 1000 行数据的文件,因为我将“FFFF”附加到特定行。附加工作正常,文件已更改。但是,当我在追加后立即重新读取文件时,并没有发生变化——它显示的是旧数据而不是新的变化。
下面是代码:
const fs = require('fs');
const parseTxt = async (txtFile) => {
const data = await fs.readFileAsync(txtFile);
const str = data.toString('utf8');
const lines = str.split('\r\n');
var ff_string = 'FFFF';
var append_FF = linedata.substring(0, line_len - 2) + ff_string + linedata.substring(line_len - 2);
replace_line(linedata, append_FF, txtFile);
/* Re-Read the File with Changed/Appended data FF */
var re_data = re_read_file(txtFile);
const re_str = re_data.toString('utf8');
const re_lines = re_str.split('\r\n');
console.log('Re Lines Data:=========',re_str);
}
parseTxt('file.txt').then(() => {
console.log('parseTxt===');
})
function replace_line(linedata, append_FF, txtFile){
fs.readFile(txtFile, 'utf8', function(err,data) {
var formatted = data.replace(linedata, append_FF);
fs.writeFile(txtFile, formatted, 'utf8', function (err) {
if (err) return console.log(err);
});
});
return;
}
function re_read_file(txtFile){
try {
const data = fs.readFileSync(txtFile)
console.log('Re-readed File data',data);
} catch (err) {
console.error(err)
}
}
变量 'linedata' 和 'line_len' 我从不同的函数中得到它,因为它是一个巨大的函数,所以我没有包含在其中。
解决方案
The reason for your issues is that writing to the file is asynchronous. Here's what happens:
// you do some magic and create a string that you'd like to write to a file
replace_line(linedata, append_FF, txtFile); // you call "write this to a file (1)
/* Re-Read the File with Changed/Appended data FF */
// you've called `replace_line`, and you get here
// but since reading/writing to the file is asynchronous, it's working somewhere
// and your code continues to execute
// you read the file again, happens immediately! check (2)
var re_data = re_read_file(txtFile);
const re_str = re_data.toString('utf8');
const re_lines = re_str.split('\r\n');
// you print the result
console.log('Re Lines Data:=========',re_str);
// you execute this method from (1)
function replace_line(linedata, append_FF, txtFile) {
// you start reading the file, but it doesn't happen immediately
// you provide a callback to execute when read is done
fs.readFile(txtFile, 'utf8', function(err,data) {
var formatted = data.replace(linedata, append_FF);
// same goes here - you start writing the file, but it's asynchronous
// you pass a callback to execute when it's done
fs.writeFile(txtFile, formatted, 'utf8', function (err) {
if (err) return console.log(err);
});
});
return;
}
function re_read_file(txtFile){ // (2)
try {
// here you use read file SYNC, so it happens immediately!
const data = fs.readFileSync(txtFile)
console.log('Re-readed File data',data);
} catch (err) {
console.error(err)
}
}
So the overall flow is like this:
- You do some string manipulation
- You try to write that to a file
- it makes asynchronous read of the file
- it makes asynchronous write of the new data
- it makes asynchronous read of the file
- You read the file synchronously (read immediately)
- You write the result of that read
- -> at some point the asynchronous reading/writing to the file is done
You should either use sync
read/write, or you should somehow wait for the updating of the document to be done and then re-read it again (Promises, await/async, callbacks - whatever you like).
推荐阅读
- construct-2 - 构造 - 对网页进行函数调用并提供稍后调用的回调函数
- javascript - 如何使用 JavaScript 在 Hackerrank 中发出 AJAX 请求?
- python-3.x - Python:提示列表中的输入字符串
- python - 从包含多个数据帧的 txt 文件中动态选择数据帧(根据索引切片数据需要人工索引)
- java - 如何解决 Swing Calculator GUI 小数错误?
- android - 如何使用 Provider 实现 Flutter 本地化?
- java - 参考功能接口的实现返回 null
- spring - 禁用 CSRF 时 Spring Security 仍然禁止 js 获取请求
- c# - 在 ComboBox 中显示 ChartType 列表 - 图表
- event-listener - 使用侦听器时查看哪个像素发生变化的最快方法