[node.js] response.end()와 response.write()

SuyoungPark·2022년 8월 16일
1

1. response.end()에 들어갈 수 있는 데이터 형식

response.end() 안에 object를 넣으면 에러가 발생하는 것을 확인하였다.

const data = {
    "main":{
        "title": "asdf",
        "description": "asdf",
        "author": "asdf",
        "date": "asdf",
        "text": "asdf",
        "img_src": "path"
    },
    "list1":{
        "title": "asdf",
        "description": "asdf",
        "author": "asdf",
        "date": "asdf",
        "text": "asdf",
        "img_src": "path"
    }
}

const dataParsed = JSON.parse(data);
response.writeHead(200);
response.end(dataparsed);    //에러남
// response.end(dataParsed.main);    //에러남
// response.end(dataParsed.main.title);    //에러 안 남 -> 웹페이지에 "asdf" 출력

오류 메시지는 다음과 같다.

0|main   | TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received an instance of Object
0|main   |     at new NodeError (node:internal/errors:372:5)
0|main   |     at write_ (node:_http_outgoing:742:11)
0|main   |     at ServerResponse.end (node:_http_outgoing:855:5)
0|main   |     at C:\Users\user\Desktop\YRS-nodejs\main.js:20:26
0|main   |     at FSReqCallback.readFileAfterClose [as oncomplete] (node:internal/fs/read_file_context:68:3) {
0|main   |   code: 'ERR_INVALID_ARG_TYPE'
0|main   | }

node.js 라이브러리의 response.end([data[, encoding]][, callback]) 항목을 보면, data의 형식은 string 혹은 Buffer가 가능하다고 명시되어 있다. response.end() 안에는 웹페이지에 출력할 내용이 들어오기 때문에 string 혹은 html 코드가 들어와야 한다. parsing된 json 파일 형식은 웹페이지에서 보여줄 수 없다.

해결방법: JSON.stringify()로 감싸주어 object 데이터 형식을 string 데이터 형식으로 바꿔 주면 된다.

response.end(JSON.stringify(dataParsed));


2. response.end()와 response.write()

두 코드가 동일하게 동작하는 것을 확인하였다.

response.writeHead(200);
response.write(JSON.stringify(dataParsed));
response.end();
response.writeHead(200);
response.end(JSON.stringify(dataParsed));

node.js의 response 객체의 메소드에는 response.end()와 response.write()가 있다. (Express.js에는 두 가지 외에 response.send()와 response.json()도 있다고 한다.)

response.end()는 서버에서 브라우저 사이의 connection을 끊는 시점을 명시한다. response.write()는 서버가 브라우저에 response를 보내주는 역할만 하고, connection에는 영향을 미치지 않는다. response.write()을 이용하면 response를 여러 번에 걸쳐 계속 보내줄 수 있으며, 모든 response를 다 보낸 후에는 response.end()를 써서 종료시점을 명시해 줘야 한다.

node.js 라이브러리의 response.end([data[, encoding]][, callback]) 항목에는 이렇게 언급되어 있다.

"If data is specified, it is similar in effect to calling response.write(data, encoding) followed by response.end(callback)."

정리하면, response를 한 번에 보낼 것인지 여러 번에 걸쳐 나누어서 보낼 것인지에 따라 사용할 수 있는 코드의 가능성이 달라진다.

response를 여러 번에 걸쳐 보낼 것이라면 response.write()을 여러 번 사용하여 내용을 전달한 다음 response.end()로 connection을 끝내면 된다.

response를 한 번에 보낼 것이라면 두 가지 선택지가 있다. response.write()와 response.end()를 연달아 쓰거나, response.end()만 사용하여 response의 전달과 connection 종료 시점 명시를 한 번에 할 수 있다.

response 내용 전달과 connection 종료 시점 명시를 분리하는 두 번째 방법이 좀더 일반적이며, response 객체의 동작방식을 잘 이해할 수 있는 방식이라고 생각한다.

References:

https://stackoverflow.com/questions/61865764/the-chunk-argument-must-be-of-type-string-or-an-instance-of-buffer

https://jos50275266.medium.com/what-is-the-difference-between-response-send-response-end-and-response-write-c0457dba3ce2

https://nodejs.org/api/http.html#class-httpserverresponse

profile
끌리는 것을 합니다

1개의 댓글

comment-user-thumbnail
2022년 9월 26일

같은 오류나서 어떻게 해결해야되나 했는데 덕분에 바로 해결했습니다. 감사합니다~

답글 달기