文件流讀取文本內(nèi)容
'use strict';
var fs = require('fs');
// 打開一個(gè)流:
var rs = fs.createReadStream('sample.txt', 'utf-8');
rs.on('data', function (chunk) {
console.log('DATA:')
console.log(chunk);
});
rs.on('end', function () {
console.log('END');
});
rs.on('error', function (err) {
console.log('ERROR: ' + err);
});
data事件可能會(huì)有多次,每次傳遞的chunk是流的一部分?jǐn)?shù)據(jù)融涣。
流的形式寫入文件
'use strict';
var fs = require('fs');
var ws1 = fs.createWriteStream('output1.txt', 'utf-8');
ws1.write('使用Stream寫入文本數(shù)據(jù)...\n');
ws1.write('END.');
ws1.end();
var ws2 = fs.createWriteStream('output2.txt');
ws2.write(new Buffer('使用Stream寫入二進(jìn)制數(shù)據(jù)...\n', 'utf-8'));
ws2.write(new Buffer('END.', 'utf-8'));
ws2.end();
所有可以讀取數(shù)據(jù)的流都繼承自stream.Readable,所有可以寫入的流都繼承自stream.Writable。
pipe
兩個(gè)流也可以串起來(lái)吹菱。一個(gè)Readable流和一個(gè)Writable流串起來(lái)后,所有的數(shù)據(jù)自動(dòng)從Readable流進(jìn)入Writable流彭则,這種操作叫pipe鳍刷。
復(fù)制文件
'use strict';
var fs = require('fs');
var rs = fs.createReadStream('sample.txt');
var ws = fs.createWriteStream('copied.txt');
rs.pipe(ws);
取消自動(dòng)關(guān)閉Writable流
readable.pipe(writable, { end: false });
read_stream.js
'use strict';
const fs = require('fs');
var rs = fs.createReadStream('sample.txt', 'utf-8');
rs.on('data', function (chunk) {
console.log('DATA:')
console.log(chunk);
});
rs.on('end', function () {
console.log('END');
});
rs.on('error', function (err) {
console.log('ERROR: ' + err);
});
write_stream.js
'use strict';
const fs = require('fs');
var ws1 = fs.createWriteStream('output1.txt', 'utf-8');
ws1.write('使用Stream寫入文本數(shù)據(jù)...\n');
ws1.write('END.');
ws1.end();
var ws2 = fs.createWriteStream('output2.txt');
ws2.write(new Buffer('使用Stream寫入二進(jìn)制數(shù)據(jù)...\n', 'utf-8'));
ws2.write(new Buffer('END.', 'utf-8'));
ws2.end();
console.log('done.');
copy_file.js
'use strict';
// read binary data from 'sample.txt'
const fs = require('fs');
var rs = fs.createReadStream('sample.txt');
var ws = fs.createWriteStream('copied.txt');
rs.pipe(ws);