节点:使用流和管道读取数据,转换数据并写入文件

时间:2016-11-15 15:11:46

标签: node.js stream fs

我尝试从文本文件中读取字符串,对其进行编码并保存到文件中。我想使用pipehashReadStream转移到WriteStream。但我不知道如何转换已更改的数据。我的代码:

const crypto = require('crypto');
const fs = require('fs');
let hash = crypto.createHash('md5');
var rs = fs.createReadStream('./passwords.txt');
var ws = fs.createWriteStream('./new_passwords.txt');


rs.on('data', function(d) {
  hash.update(d);
});
rs.on('end', function(d) {
    console.log(hash.digest('hex'))
});

2 个答案:

答案 0 :(得分:3)

根据the documentation,它应该像以下一样简单:

const fs = require('fs')
const crypto = require('crypto')
const hash = crypto.createHash('md5')
const rs = fs.createReadStream('./plain.txt')
const ws = fs.createWriteStream('./hashed.txt')

rs.pipe(hash).pipe(ws)

答案 1 :(得分:2)

var rs = fs.createReadStream('./passwords.txt');
var ws = fs.createWriteStream('./new_passwords.txt');
var Transform = require('stream').Transform;
var transformer = new Transform();

transformer._transform = function(data, encoding, cb) {
 // do transformation
 cb();
}

    rs
    .pipe(transformer)
    .pipe(ws);