我有一个大小未知的文件 test.txt。与其他服务共享文件,我必须读取该文件才能编辑它。只是将时间戳更改为现在的小编辑。 编辑它而不读取整个文件并再次重写的最佳方法是什么?我不认为这是正确的做法。我知道 createReadStream 和 createWriteStream 但我不想复制文件并浪费资源,尤其是内存。 谢谢。
最佳答案
我不知道有什么方法可以读取要更改的文件内容,而无需至少打开文件,更改需要更改的内容,然后重新写入它。 Node 中执行此操作的最有效和性能最高的方法是通过流,因为您不需要一次读取整个文件。假设您需要编辑的文件有一个新行或回车符,您可以使用 Readline 模块逐行迭代有问题的文件,并检查该行是否包含您要更改的文本。然后您可以将该数据写入文件中旧文本所在的位置。
如果您没有换行符,您可以选择使用 Transform Stream
并检查每个 block 是否有匹配的文本,但这可能需要将多个 block 拼接在一起以识别要替换的文本。
我知道您或多或少不想复制所做更改的文件,但我无法想出另一种同样有效的方法。
const fs = require('fs')
const readline = require('readline')
const outputFile = fs.createWriteStream('./output-file.txt')
const rl = readline.createInterface({
input: fs.createReadStream('./input-file.txt')
})
// Handle any error that occurs on the write stream
outputFile.on('err', err => {
// handle error
console.log(err)
})
// Once done writing, rename the output to be the input file name
outputFile.on('close', () => {
console.log('done writing')
fs.rename('./output-file.txt', './input-file.txt', err => {
if (err) {
// handle error
console.log(err)
} else {
console.log('renamed file')
}
})
})
// Read the file and replace any text that matches
rl.on('line', line => {
let text = line
// Do some evaluation to determine if the text matches
if (text.includes('replace this text')) {
// Replace current line text with new text
text = 'the text has been replaced'
}
// write text to the output file stream with new line character
outputFile.write(`${text}\n`)
})
// Done reading the input, call end() on the write stream
rl.on('close', () => {
outputFile.end()
})
关于javascript - 编辑 Node 中的大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44265722/