gpt4 book ai didi

javascript - 使用 JS 和 Node 读写文件

转载 作者:行者123 更新时间:2023-12-03 03:11:24 25 4
gpt4 key购买 nike

我正在尝试编写一个读取文件的函数,当它找到特定行时,它会删除其下面的所有内容,然后附加另一组行。我已设法读取文件并找到我需要的字符串:

function read() {
lineReader.on('line', function (line) {
console.log('Line from file: ' + line)
if(line.trim() === 'Examples:'){
console.log('Found what I needed, delete everything below this line');
}
});
}

我看不到的是如何删除此行下方的所有内容,然后附加我需要的文本。我是 JSNode.js 的新手。

最佳答案

您可以通过同时打开文件写入流来完成此操作。

在 lineReader 事件处理程序中,将“Example”之前的所有行放入单独的文件流中。当示例出现时,只需将所需的行集附加到第二个文件流中并关闭 lineReader。

所以添加这样的内容:

// before the code
var writer = fs.createWriteStream('new.txt');
// load custom lines from customLines.txt
var customLines = fs.readFileSync('customLines.txt');

// in the on('line') callback:
writer.write(line + "\n");

// if 'Examples:' was found:
writer.write(customLines);
writer.end();
lineReader.close();

关于javascript - 使用 JS 和 Node 读写文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46936201/

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