Jak tworzyć strumienie z ciągu znaków w węźle.Js?

Używam biblioteki ya-csv, która oczekuje pliku lub strumienia jako wejścia, ale mam ciąg znaków.

Jak przekonwertować ten łańcuch na strumień w Node?

Author: Morten Siebuhr, 2012-10-06

9 answers

Jak @ substack poprawiłem mnie w # node , Nowy streams API w Node v10 ułatwia to:

const Readable = require('stream').Readable;
const s = new Readable();
s._read = () => {}; // redundant? see update below
s.push('your text here');
s.push(null);

... po czym można dowolnie rurkę lub w inny sposób przekazać ją zamierzonemu konsumentowi.

Nie jest tak czysty jak resumer one-liner, ale pozwala uniknąć dodatkowej zależności.

(Update: w wersjach v0.10.26 do V9.2.1 Jak dotąd, wywołanie push bezpośrednio z monitu REPL ulegnie awarii z wyjątkiem not implemented jeśli nie ustawiłeś _read. Nie spowoduje awarii wewnątrz funkcji lub skryptu. Jeśli niespójność Cię denerwuje, Dołącz noop.)

 134
Author: Garth Kidd,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-06 20:33:15

Nie używaj odpowiedzi życiorysu Jo Lissa. To będzie działać w większości przypadków, ale w moim przypadku stracił mi Dobre 4 lub 5 godzin wykrywania błędów. Nie ma potrzeby stosowania modułów innych firm.

NOWA ODPOWIEDŹ :

var Readable = require('stream').Readable

var s = new Readable
s.push('beep')    // the string you want
s.push(null)      // indicates end-of-file basically - the end of the stream

Powinien to być w pełni zgodny strumień czytelny. Zobacz tutaj aby uzyskać więcej informacji na temat Prawidłowego Korzystania ze strumieni.

STARA ODPOWIEDŹ : Po prostu użyj natywnego strumienia PassThrough:

var stream = require("stream")
var a = new stream.PassThrough()
a.write("your string")
a.end()

a.pipe(process.stdout) // piping will work as normal
/*stream.on('data', function(x) {
   // using the 'data' event works too
   console.log('data '+x)
})*/
/*setTimeout(function() {
   // you can even pipe after the scheduler has had time to do other things
   a.pipe(process.stdout) 
},100)*/

a.on('end', function() {
    console.log('ended') // the end event will be called properly
})

Zauważ, że zdarzenie "close" nie jest emitowane (co jest nie jest wymagane przez interfejsy strumienia).

 84
Author: B T,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-08 21:29:50

Po prostu utwórz nową instancję stream i dostosuj ją do swoich potrzeb:

var Stream = require('stream');
var stream = new Stream();

stream.pipe = function(dest) {
  dest.write('your string');
  return dest;
};

stream.pipe(process.stdout); // in this case the terminal, change to ya-csv

Lub

var Stream = require('stream');
var stream = new Stream();

stream.on('data', function(data) {
  process.stdout.write(data); // change process.stdout to ya-csv
});

stream.emit('data', 'this is my string');
 28
Author: zemirco,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-06 11:03:25

Edytuj: odpowiedź Gartha jest chyba lepsza.

Mój stary tekst odpowiedzi jest zachowany poniżej.


Aby przekonwertować łańcuch znaków na strumień, możesz użyć wstrzymanego poprzez stream:

through().pause().queue('your string').end()

Przykład:

var through = require('through')

// Create a paused stream and buffer some data into it:
var stream = through().pause().queue('your string').end()

// Pass stream around:
callback(null, stream)

// Now that a consumer has attached, remember to resume the stream:
stream.resume()
 12
Author: Jo Liss,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:02:45

Jest do tego moduł: https://gist.github.com/kawanet/8aea35dc4a578f09757d

/**
* @see https://www.npmjs.com/package/string-to-stream
*/
var str = require('string-to-stream')
str('hi there').pipe(process.stdout) // => 'hi there' 
 9
Author: Lori,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-30 23:44:48

W kawie-scenariusz:

class StringStream extends Readable
  constructor: (@str) ->
    super()

  _read: (size) ->
    @push @str
    @push null

Użyj go:

new StringStream('text here').pipe(stream1).pipe(stream2)
 6
Author: xinthink,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-23 08:11:16

Zmęczyło mnie, że muszę uczyć się tego co pół roku, więc właśnie opublikowałem moduł npm, aby wyodrębnić szczegóły implementacji:

Https://www.npmjs.com/package/streamify-string

To jest rdzeń modułu:

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

function Streamify(str, options) {

  if (! (this instanceof Streamify)) {
    return new Streamify(str, options);
  }

  Readable.call(this, options);
  this.str = str;
}

util.inherits(Streamify, Readable);

Streamify.prototype._read = function (size) {

  var chunk = this.str.slice(0, size);

  if (chunk) {
    this.str = this.str.slice(size);
    this.push(chunk);
  }

  else {
    this.push(null);
  }

};

module.exports = Streamify;

str jest string, które muszą zostać przekazane konstruktorowi podczas wywołania i będą wyprowadzane przez strumień jako dane. options są typowymi opcjami, które mogą być przekazywane do strumienia, na dokumentacja .

Według Travisa CI, powinien być kompatybilny z większością wersji node.

 3
Author: Chris Allen Lane,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-16 12:33:41

Innym rozwiązaniem jest przekazanie funkcji read do konstruktora Readable (cf doc stream readable options)

var s = new Readable({read(size) {
    this.push("your string here")
    this.push(null)
  }});

Możesz po użyciu s. pipe dla exemple

 3
Author: Philippe T.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-04 11:00:03

JavaScript jest pisany kaczką, więc jeśli po prostu skopiujesz czytelny API strumienia , będzie działać dobrze. W rzeczywistości prawdopodobnie nie możesz zaimplementować większości z tych metod lub po prostu pozostawić je jako stuby; wszystko, czego potrzebujesz, aby zaimplementować, to to, czego używa biblioteka. Możesz użyć wstępnie zbudowanego węzła EventEmitter klasa do radzenia sobie również z wydarzeniami, więc nie musisz wdrażać addListener i tego typu siebie.

Oto jak możesz zaimplementować to w CoffeeScript:
class StringStream extends require('events').EventEmitter
  constructor: (@string) -> super()

  readable: true
  writable: false

  setEncoding: -> throw 'not implemented'
  pause: ->    # nothing to do
  resume: ->   # nothing to do
  destroy: ->  # nothing to do
  pipe: -> throw 'not implemented'

  send: ->
    @emit 'data', @string
    @emit 'end'

Wtedy możesz użyć go jak więc:

stream = new StringStream someString
doSomethingWith stream
stream.send()
 1
Author: icktoofay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-10-06 02:12:02