最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - node.js modify file data stream? - Stack Overflow

programmeradmin3浏览0评论

I need to copy one large data file to another destination with some modifications. fs.readFile and fs.writeFile are very slow. I need to read line by line, modify and write to new file. I found something like this:

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));
})

But how to make modifications ? I tried to get data with data event

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

but don't understand how to write it to file:

I need to copy one large data file to another destination with some modifications. fs.readFile and fs.writeFile are very slow. I need to read line by line, modify and write to new file. I found something like this:

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));
})

But how to make modifications ? I tried to get data with data event

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

but don't understand how to write it to file:

Share Improve this question asked Aug 19, 2017 at 19:18 ArtiArti 7,77213 gold badges61 silver badges132 bronze badges 1
  • 1 through2 can help you. The first example code pretty much shows exactly what you want to do. – robertklep Commented Aug 19, 2017 at 20:14
Add a ment  | 

1 Answer 1

Reset to default 13

You should use transform stream and use pipes like this:

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

Then it's just a matter of implementing the transform stream as in this doc

You can also make this easier for you using scramjet like this:

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'))

Which I suppose is easier than doing that manually.

发布评论

评论列表(0)

  1. 暂无评论