簡體   English   中英

node.js修改文件數據流?

[英]node.js modify file data stream?

我需要將一個大型數據文件復制到另一個目的地並進行一些修改。 fs.readFilefs.writeFile非常慢。 我需要逐行閱讀,修改並寫入新文件。 我找到了這樣的東西:

fs.stat(sourceFile, function(err, stat){
    var filesize = stat.size;

    var readStream = fs.createReadStream(sourceFile);

    // HERE I want do some modifications with bytes

    readStream.pipe(fs.createWriteStream(destFile));
})

但是如何進行修改? 我試圖用data事件獲取數據

readStream.on('data', function(buffer){
    var str = strToBytes(buffer);
    str.replace('hello', '');
    // How to write ???
});

但不明白如何將其寫入文件:

您應該使用transform流並使用這樣的管道:

fs.createReadStream('input/file.txt')
     .pipe(new YourTransformStream())
     .pipe(fs.createWriteStream('output/file.txt'))

然后,這只是在本文檔實現轉換流的問題

你也可以使用scramjet這樣更容易:

fs.createReadStream('input/file.txt')
     .pipe(new StringStream('utf-8'))
     .split('\n')                                          // split every line
     .map(async (line) => await makeYourChangesTo(line))   // update the lines
     .join('\n')                                           // join again
     .pipe(fs.createWriteStream('output/file.txt'))

我認為這比手動操作更容易。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM