例子1
const fs = require("fs");
const stream = fs.createWriteStream("./big_file.txt");
for(let i = 0; i < 10000; i++){
stream.write(`这是${i}行内容,测试测试\n`);
}
stream.end();
console.log('done');
Steam-流
例子2\3
const http = require("http");
const server = http.createServer();
server.on('request',(request,response)=>{
fs.readFile('./big_file.txt',(error,data)=>{
if(error) throw error;
response.end(data);
console.log('node');
});
})
server.listen(8888);
const http = require("http");
const fs = require("fs");
const server = http.createServer();
server.on('request',(request,response)=>{
const stream = fs.createReadStream("./big_file.txt");
stream.pipe(response);
})
server.listen(8888);
管道
Stream对象的原型链
Stream的分类
自创流
const { Writable} = require("stream");
const outStream = new Writable({
write(chunk,encoding,callback){
console.log(chunk.toString());
callback();
}
})
process.stdin.pipe(outStream);