https://nodejs.org/api/stream.html https://nodesource.com/blog/understanding-object-streams/ 를 참고하여 작성했습니다.
기본적으로 스트림은 String과 Buffer만 다룰 수 있지만, 상황에 따라 javascript object를 받을 수 있게 설정할 수 있다.
objectMode를 활성화 시킨다면, 내부 버퍼링 알고리즘이 bytes로 계산하던 방식이 object 개수로 계산하게 된다. 이 말은 highWaterMark도 object 개수로 판단한다.
아래 예시에서 stream을 잘 활용하기 위한 library를 사용한다.
const through2 = require('through2')
const split2 = require('split2')
const stream = through2({objectMode:true}, function (chunk, enc, callback) {
const string = chunk.toString()
const result = string.replace('/\n/', '').toUpperCase().split(/[ \t]/)
this.push(result)
callback()
})
stream.on('data', function (data) {
const toString = Object.prototype.toString.call(data)
console.log('type of data', toString)
console.log('data: ', data, '\n')
})
process.stdin.pipe(split2()).pipe(stream)
output
Hello world
type of data: [object Array]
data: ["HELLO", "WORLD"]
Transform streams are great!
type of data: [object Array]
data: ["TRANSFORM", "STREAMS", "ARE", "GREAT!"]
다른 스트림과 함께 사용하기
object-stream에서 non-object stream에 데이터를 보낼 경우 에러가 발생한다.
이유는 non-object stream은 String와 Buffer만 받을 수 있기 때문이다.
이를 해결하기 위해서 중간에 새로운 스트림을 만들어 object에서 String 또는 Buffer로 변환해주는 로직을 추가한다.
const through2 = require('through2')
const stream = through2.obj(function (chunk, enc, callback) {
chunk.timestamp = new Date()
this.push(chunk)
callback()
})
const jsonStream = through2.obj(function (chunk, encoding, callback) {
this.push(JSON.stringify(chunk, null, 4) + '\n')
callback()
})
stream.pipe(jsonStream).pipe(process.stdout)
stream.write({status: 404, message: 'NOT FOUND'})
stream.write({status: 500, message: 'INTERNAL ERROR'})
output
{
"status": 404,
"message": "NOT FOUND",
"timestamp": "2024-05-03T07:54:55.457Z"
}
{
"status": 500,
"message": "INTERNAL ERROR",
"timestamp": "2024-05-03T07:54:55.457Z"
}
언제 Object Stream이 유용할까?
raw data를 받아 사람이 읽을 수 있는 문자로 변환해주는 작업을 할 때
ex) Protocol Parser, cvs-parse, database records
'IT > node.js' 카테고리의 다른 글
| [node.js] stream - three states (5) (0) | 2024.05.05 |
|---|---|
| [node.js] readable stream - two modes (4) (0) | 2024.05.05 |
| [node.js] stream - buffering (3) (1) | 2024.05.04 |
| [node.js] stream api - sample code (1) (0) | 2024.05.03 |
| node.js, single thread 아닌가요? (1) | 2024.05.03 |