четверг, 27 июня 2019 г.

Node.js - Streams Readable / Writable

Node.js Stream Readable

var Readable = require('stream').Readable;

var rs = new Readable();


rs.push('beep ');
rs.push('boop');
rs.push(null);
rs.pipe(process.stdout);


var c = 97;
rs._read = function () {
    if (c >= 'z'.charCodeAt(0)) {
        return rs.push(null);
    }
    setTimeout(function () {
        rs.push(String.fromCharCode(++c));
    }, 100);
};
rs.on('data', function (data) {console.log(data.toString());});
rs.on('end', function (data) {console.log('END');});


Node.js Stream Writable

var Writable = require('stream').Writable;

var ws = Writable();
ws._write = function (chunk, enc, next) {
    console.log(chunk.toString());
    next();
};
process.stdin.pipe(ws);


var fs = require('fs');
var ws = fs.createWriteStream('./message.txt');
ws.write('beep ');
setTimeout(function () {
    ws.end('boop');
}, 1000);

Examples

// ------------------------------------------------- //

var fs = require('fs');

var readStream = fs.createReadStream('./big-file.txt');

// Read stream, the "data" way

readStream.on('data', function (chunk) {
    // do something with chunk
});

readStream.on('end', function () {
    // stream finished
});

// ------------------------------------------------- //

// Read stream, the "readable" way

readStream.on('readable', function () {
    var chunk;
    while ((chunk = readStream.read()) !== null) {
        // do something with chunk
    }
});

readStream.on('end', function () {
    // stream finished
});

// ------------------------------------------------- //

var http = require('http');
var fs = require('fs');

var server = http.createServer();

server.on('request', function (request, response) {
    fs.createReadStream('./big-file.txt').pipe(response);
});

server.listen(8000, '127.0.0.1');

// ------------------------------------------------- //

var http = require('http');
var fs = require('fs');
var stream = require('stream');

var server = http.createServer();

server.on('request', function (request, response) {
    // automatically deastroy response if there is an error
    stream.pipeline(fs.createReadStream('./big-file.txt'), response, function (error) {
        if (error) {console.error(error);}
    });
});

server.listen(8000, '127.0.0.1');

1 комментарий: