[javascript] Node.Js의 문자열에서 스트림을 만드는 방법은 무엇입니까?

파일 또는 스트림을 입력으로 예상하는 ya-csv 라이브러리를 사용하고 있지만 문자열이 있습니다.

노드에서 해당 문자열을 스트림으로 어떻게 변환합니까?



답변

노드 10.17부터 stream.Readable은 fromiterable (배열 리터럴 포함)에서 쉽게 스트림을 생성 하는 방법을 가지고 있습니다.

const { Readable } = require("stream")

const readable = Readable.from(["input string"])

readable.on("data", (chunk) => {
  console.log(chunk) // will be called once with `"input string"`
})

최소한 10.17과 12.3 사이에서 문자열 자체는 반복 가능하므로 Readable.from("input string") 작동하지만 문자 당 하나의 이벤트를 생성합니다. Readable.from(["input string"])배열의 항목 당 하나의 이벤트 (이 경우 하나의 항목)를 생성합니다.

또한 이후 노드 (아마도 12.3, 문서에서 함수가 변경되었다고 말했기 때문에)에서 더 이상 문자열을 배열로 래핑 할 필요가 없습니다.

https://nodejs.org/api/stream.html#stream_stream_readable_from_iterable_options


답변

으로 @substack이 저를 수정 #node , 새로운 스트림 API 노드 V10에이 쉽게 :

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

그 후에 자유롭게 파이프를 만들거나 원하는 소비자에게 전달할 수 있습니다.

이력서줄짜리 만큼 깨끗 하지는 않지만 여분의 의존성을 피합니다.

( 업데이트 : v0.10.26부터 v9.2.1까지는 설정하지 않은 경우 pushREPL 프롬프트에서 직접 호출 하면 not implemented예외 가 발생합니다 _read. 함수 나 스크립트 내에서 충돌 하지 않습니다 . 긴장, 포함하십시오 noop.)


답변

Jo Liss의 이력서 답변을 사용하지 마십시오. 대부분의 경우 작동하지만 제 경우에는 4 ~ 5 시간 동안 버그를 찾지 못했습니다. 이를 위해 타사 모듈이 필요하지 않습니다.

새로운 답변 :

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

이것은 완전 호환 가능한 읽기 가능 스트림이어야합니다. 스트림을 올바르게 사용하는 방법에 대한 자세한 내용은 여기참조하십시오 .

구식 답변 : 기본 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
})

‘close’이벤트는 생성되지 않습니다 (스트림 인터페이스에는 필요하지 않음).


답변

stream모듈 의 새 인스턴스를 만들고 필요에 따라 사용자 정의하십시오.

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

또는

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');


답변

편집 : Garth의 대답 이 더 낫습니다.

내 이전 답변 텍스트는 아래에 유지됩니다.


스트림에 문자열을 변환하려면, 당신은이 일시 사용 을 통해 스트림 :

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

예:

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()


답변

그 모듈이 있습니다 : https://www.npmjs.com/package/string-to-stream

var str = require('string-to-stream')
str('hi there').pipe(process.stdout) // => 'hi there' 


답변

커피 스크립트에서 :

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

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

그걸 써:

new StringStream('text here').pipe(stream1).pipe(stream2)