One character in a time stream with node

I am trying to implement a stream that returns one character from a file for each data event. I ended up with the code below:

var util = require('util'),
    fs = require('fs'),
    Readable = require('stream').Readable;

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

var SymbolReadStream = function(filename, options) {
  Readable.call(this);
  this._readable = fs.createReadStream(filename, options).pause();
  self = this;
  this._readable.on('readable', function() {
    var chunk;
    chunk = self._readable.read(1);
    // I believe the problem is here
    self._readable.pause();
  });
};

util.inherits(SymbolReadStream, Readable); // inherit the prototype methods

SymbolReadStream.prototype._read = function() {
  this._readable.resume();
};

var r = new SymbolReadStream("test.txt", {
  encoding: 'utf8',
});
r.on('data', function(el) {
  console.log(el);
});

but this code does not work. Please help. Is there an easier way to achieve this behavior?

0
source share
2 answers

In your streaming implementation, the data event for the handler is not dispatched. Because of this, they are console.lognever called. After adding events, they will be transmitted symbol by symbol. Example below:

var util = require('util'),
  fs = require('fs'),
  Readable = require('stream').Readable;

function SymbolReadStream(filename, options) {
  if (!(this instanceof SymbolReadStream)) {
    return new SymbolReadStream(length, options);
  }

  Readable.call(this);
  this._readable = fs.createReadStream(filename, options);
}

util.inherits(SymbolReadStream, Readable); // inherit the prototype methods

SymbolReadStream.prototype._read = function() {
  var self = this;
  this._readable.on('readable', function() {
    var chunk;
    while (null !== (chunk = self._readable.read(1))) {
      self.emit('data', chunk);
    }
  });
  this._readable.on('end', function() {
    self.emit('end');
  });
};

var r = new SymbolReadStream("test.txt", {
  encoding: 'utf8',
});
r.on('data', function(el) {
  console.log(el);
});
r.on('end', function(el) {
  console.log('done');
});
+1
source

This post provides a great tip on how to answer your question.

, pipe, , :

, , , . "" , char, . event-stream split, , string.split, , "\n" ",". , myStream.pipe(es.split('')), myStream.pipe(es.split()), . , , , " char"

var es = require('event-stream');
var fs = require('fs');

var symbolStream = fs.createReadStream(filename, options).pipe(es.split(/(?!$)/));

EDIT: , , split ,

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

var symbolStream = fs.createReadStream(filename, options).pipe(split(/(?!$)/));

( '' \r\n)

+3

All Articles