2017-05-30 47 views
-1

我有一個未知大小的文件test.txt。與其他服務共享文件,我必須從這個文件讀取編輯它。只需稍稍編輯即可更改時間戳。 什麼是編輯它而不讀取整個文件並重新寫入的最佳方式。我不認爲這是一個正確的方法來做到這一點。我知道createReadStream和createWriteStream,但我不想複製文件並浪費資源,特別是內存。 謝謝。編輯節點中的大文件

+0

沒有測試,只是快速搜索:https://stackoverflow.com/questions/14177087/replace-a-string-in-a-file-with-nodejs – dward

+1

@dward - 對接受的答案問題究竟是什麼這個問題試圖避免 – Quentin

+1

使用流不會浪費大量的內存。 – SLaks

回答

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

是的,謝謝,但這裏的時間戳是比喻,我的真實情況是一個字符串將被改爲另一個隨機字符串。 – jalal246

+0

@JimmyJanson所以你想改變文件的內容,對吧?我以爲只是想改變文件時間戳。 –

+0

是的,我認爲把時間戳的內容使問題更容易理解。 – jalal246

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