我有一個未知大小的文件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