[英]Read/Write File in a Nodejs
我有一個包含大約 3600 行的 Hex 文件。 現在我在文件中有一個單詞 1000 需要搜索並閱讀該文本的確切上述行。 例如:
1:2007200040040020A006000000050020A806000010050020B0060000101E0
2:2007400000020020C0060000EC010020C7060000F0010020CE060000F8010
3:04076000040200206F
4:20**1000**00B41200001810000015AB0110FDB301106DC00110FDAE011099B501
5:08102000000000002D0000009B
6:20102800B01200003C100000B1C00110A9BF011067C0011069B801
7:041048003000000074
現在在上述數據中,1000 位於第 4 行,並從該搜索操作中獲取第 3 行數據。
我正在使用 nodejs FS 庫。
到目前為止,以下是我的代碼:
const parseTxt = async (csvFile) => {
const data = await fs.readFileAsync(csvFile);
const str = data.toString();
const lines = str.split('\r\n');
var total_lines = lines.length;
console.log('Total Lines', total_lines);
lines.map(line => {
if(!line) {return null}
result.push(Number(line))
});
lines.forEach(linebyline => {
var search1000 = linebyline.substring(3, 7);
if(search1000 == '1000'){
// Here I want to check line number of this search and also above line data as well as line number of that above line.
// Also want to Append "DOWNLOAD" text starting of this line data.
}
});
}
parseTxt('file.hex').then(() => {
// console.log(mergeSort({arr: result, count: 0}));
console.log('parseTxt===');
})
謝謝你。
const fs = require('fs');
const readline = require('readline');
async function findPreviousLine(filename, searchString) {
const fileStream = fs.createReadStream(filename);
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
let previousLine = '';
for await (const line of rl) {
if (line.includes(searchString)) {
console.log(previousLine)
return;
}
previousLine = line;
}
}
findPreviousLine('data.txt', '1000');
請參閱此答案中的代碼以逐行閱讀。
這是工作示例
const fs = require('fs');
const parseTxt = async (csvFile) => {
let result=[];
const data = await fs.readFileSync(csvFile);
const str = data.toString();
const lines = str.split('\n');
var total_lines = lines.length;
lines.map(line => {
if(!line) {return null}
result.push(Number(line))
});
lines.forEach(linebyline => {
var search1000 = linebyline.indexOf('1000');
if(search1000 > -1){
// Here I want to check line number of this search and also above line data as well as line number of that above line.
// Also want to Append "DOWNLOAD" text starting of this line data.
}
});
}
parseTxt('file.hex').then(() => {
// console.log(mergeSort({arr: result, count: 0}));
console.log('parseTxt===');
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.