스트림을 파이프로 연결하는 방법은 무엇입니까?
Node.js의 스트림
This is the second article of a series about streams in Node.js. It explains what pipe does in Node.js, and how to connect streams using pipe.
Streams in Node.js
파이프로 스트림 연결
The recommended way to consume streams is the pipe and pipeline methods, which consume streams and handle the underlying events for you. To connect streams together and start the flow of data, the pipe method is available on readable streams. It is also possible to listen to stream events, but it is not recommended for consuming data. The main goal of pipe is to limit the buffering of data so that sources and destinations will not overwhelm the available memory.
The pipe method uses, under the hood, the events emitted by streams and abstracts away the need to handle these events. The only exception is, that the handling of error events is not included in the abstraction and has to be done separate. Unhandled stream errors can crash your application.
pipe method is available on streams, which implement a Readable interface. Check out the article What is a Stream in Node.js? 다른 유형의 스트림에 대해.Readable , Duplex , Transform 및 PassThrough 스트림은
Readable 인터페이스를 구현합니다. 이 메서드는 데이터를 파이프할 대상을 수락합니다. 대상 스트림은 Writable 인터페이스를 구현해야 합니다. Writable , Duplex , Transform 및 PassThrough 스트림은 Writable 인터페이스를 구현합니다.예를 들어 보겠습니다. 노드에는 전역적으로 사용 가능한 읽기 가능한 스트림
process.stdin(stdin은 표준 입력을 나타냄)과 쓰기 가능한 스트림process.stdout(stdout은 표준 출력을 나타냄)이 있습니다.파일을 생성합니다(또는 REPL 사용).
touch stream-it.js
여기에 다음 코드를 추가합니다.
process.stdin.pipe(process.stdout);
그런 다음 CLI
node stream-it.js에서 실행하고 Banana를 입력하고 Enter 키를 누르십시오. Banana가 다시 표시되는 것을 볼 수 있습니다.무슨 일이 일어나고 있는지 설명하겠습니다.
process.stdin는 읽을 수 있는 데이터 소스이고 process.stdout는 쓰기 가능한 대상입니다. 텍스트를 입력하면 텍스트가 stdin에서 stdout로 파이프되어 에코가 생성됩니다. pipe를 호출하면 대상 스트림이 반환됩니다.pipe 메서드를 사용하면 여러 스트림을 함께 연결할 수 있습니다. 이에 대한 요구 사항은 대상 스트림이 Duplex , Transform 및 PassThrough 와 같이 읽고 쓸 수 있어야 한다는 것입니다.const { PassThrough } = require('stream');
const passThrough = new PassThrough();
process.stdin.pipe(passThrough).pipe(process.stdout);
fs 모듈을 사용하여 파일에서 스트림 생성
Implementing streaming interfaces and consuming streams have quite a few differences. Creating streams is not as common as consuming streams, but there are some instances where creating your own stream is useful. The most common use cases is streaming data from and to a file using the fs module.
The fs module is able to create read and writeable streams using the helper methods fs.createReadStream and fs.createWriteStream . The method createWriteStream takes a file path as the first argument, and then optional config arguments.
Let's dive into code and create a simple stream that writes text from stdin to a file called output.txt .
Create a file.
touch stream-to-file.js
Add code.
const fs = require('fs');
const outputStream = fs.createWriteStream('output.txt');
process.stdin.pipe(outputStream);
Run the code in the CLI with node stream-to-file.js and type Hello Stream and hit the enter key. Then log the output.txt to the console with cat output.txt or open the file in a text editor. You will see that Hello Stream was written to the file. In this example, we have replaced the stdout with the variable outputStream which holds the stream created with fs.createWriteStream .
Since there is some data now in the output.txt file, let's invert this and create a readable stream with piping the data from output.txt .
Create a file.
touch stream-out.js
Add code.
const fs = require('fs');
const inputFileStream = fs.createReadStream('output.txt');
inputFileStream.pipe(process.stdout);
Run the file with node stream-out.js and you will see the text from the output.txt file written in the terminal.
{flags: 'a'}를 전달할 수 있습니다. 파일이 없으면 생성됩니다.const fs = require('fs');
const outputStream = fs.createWriteStream('output.txt', {
flags: 'a',
});
process.stdin.pipe(outputStream);
파일이 이미 존재하는 경우 파일에 데이터를 추가하고 그렇지 않으면 파일을 생성합니다.
TL;DR
- The recommended way to consume streams is the
pipeandpipelinemethod. - The main goal of
pipeis to limit the buffering of data so memory will not be overloaded. - The
pipemethod is available on streams, which implement aReadableinterface. - With the help of
pipestreams can be chained. - The
fsmodule can create readable and writeable streams.
Thanks for reading and if you have any questions , use the comment function or send me a message .
If you want to know more about Node , 이것들을 보세요 Node Tutorials .참조(그리고 큰 감사):
HeyNode , Node.js - Streams , MDN - Streams Node.js - fs
Reference
이 문제에 관하여(스트림을 파이프로 연결하는 방법은 무엇입니까?), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/mariokandut/how-to-connect-streams-with-pipe-3j6p텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)