node.js修改文件数据流?
node.js modify file data stream?
我需要将一个大型数据文件复制到另一个目的地并进行一些修改。 fs.readFile
和 fs.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'))
那就是implementing the transform stream as in this doc
的问题了
您也可以像这样使用 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'))
我认为这比手动操作更容易。
我需要将一个大型数据文件复制到另一个目的地并进行一些修改。 fs.readFile
和 fs.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'))
那就是implementing the transform stream as in this doc
的问题了您也可以像这样使用 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'))
我认为这比手动操作更容易。