我有一个未知大小的文件test.txt。与其他服务共享文件,我必须从这个文件读取编辑它。只需稍稍编辑即可更改时间戳。 什么是编辑它而不读取整个文件并重新写入的最佳方式。我不认为这是一个正确的方法来做到这一点。我知道createReadStream和createWriteStream,但我不想复制文件并浪费资源,特别是内存。 谢谢。编辑节点中的大文件
-1
A
回答
0
如果你只是想改变时间戳,你可以使用fs.futimes()
。版本号为v0.4.2
的节点为原生节点。
var fs = require("fs");
var fd = fs.openSync("file"); // Open a file descriptor
var now = Date.now()/1000;
fs.futimesSync(fd, now, now); // Modify it by (fd, access_time, modify_time)
fs.closeSync(fd); // Close file descriptor
这样,你不依赖于任何NPM包。
你可以在这里阅读更多:https://nodejs.org/api/fs.html#fs_fs_futimes_fd_atime_mtime_callback
0
你需要像触摸Linux命令行,有一个npm package正是这一点做的。
1
我不知道如何在不打开文件的情况下阅读文件内容进行更改,更改需要更改的内容然后重新写入。 Node中这样做的最有效和高效的方式是通过流,因为您不需要一次读取整个文件。假设你需要编辑的文件有一个新行或回车符,你可以使用Readline模块逐行回答问题文件,并检查该行是否包含你想改变的文本。然后,您可以将该数据写入旧文本所在的文件。
如果您没有换行符,您可以选择使用Transform Stream
并检查每个块的匹配文本,但这可能需要将多个块拼接在一起以识别要替换的文本。
我知道你不想或多或少地将文件复制到所做的更改中,但我无法想出另一种效率更高的方法。
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()
})
+1
好吧,它结束了类似于你的建议,找不到更好的东西。 谢谢 – jalal246
相关问题
- 1. 节点文本编辑
- 2. 如何用节点js编辑文件?
- 3. 编辑Xml节点
- 4. 编辑倍数节点的XML文件中的相同属性
- 5. drupal编辑节点的附件字段
- 6. 如何编辑文件对象中的XML节点,使用Java
- 7. simplexml的编辑CDATA节点
- 8. 编辑XML文件(删除节点并添加新文件)
- 9. 在pdf文件中编辑字节
- 10. Kendoui treeview节点双击事件编辑
- 11. 编辑节点中的xml属性
- 12. 编辑链接列表中的节点
- 13. python中的libxml2编辑特定节点
- 14. JTree编辑根节点?
- 15. “刀节点编辑”失败
- 16. 如何编辑节点图?
- 17. PHP XML编辑CDATA节点
- 18. 节点图编辑器
- 19. 节点编辑器和节点中的密码问题
- 20. 如何编辑JS中html节点的子节点?
- 21. 编辑大量的文本文件
- 22. 编辑节点库文件的最佳方法是什么?
- 23. JTree节点渲染器和节点编辑器中的多个组件
- 24. 在VirtualTreeView中编辑根节点celltext
- 25. 在excel中编辑节点TreeView VBA
- 26. 如何在SWT中编辑树节点
- 27. (节点)点击最大文件限制?
- 28. 节点 - 编辑特定文件后重新启动服务器
- 29. 编辑节点js文件而不重新启动服务器
- 30. 如何监视xml文件(添加 - 编辑 - 删除)节点
没有测试,只是快速搜索:https://stackoverflow.com/questions/14177087/replace-a-string-in-a-file-with-nodejs – dward
@dward - 对接受的答案问题究竟是什么这个问题试图避免 – Quentin
使用流不会浪费大量的内存。 – SLaks