[Node.js] nodemon에 의한 socket hang up 에러 해결

Profile-exe·2023년 4월 9일
0

NodeJS

목록 보기
1/3
post-thumbnail

Node.js 강의를 듣는 도중 socket hang up 오류가 났다. nodemonignore 옵션을 통해 해결한 과정을 기록했다.


🚨 문제 발생

admin/add-product에서 POST로 넘긴 데이터를 fs 모듈을 이용해 data/products.json에 작성 후 / 경로로 redirect하는 과정에서 발생했다.

디버거를 돌려보니 파일에 정상적으로 데이터가 기록되어 fs모듈을 사용한 코드의 문제는 아니었다. /redirect순간 같은 코드가 반복되며 클라이언트에 응답을 주지 못하고 있었다. 그래서 timeout으로 인해 socket hang up이 발생한 것이었다.


🔍 원인 찾기

console.log로 로깅을 하며 터미널을 보고 있었는데, 원인이 될만한 점을 찾게 되었다.

[nodemon] restarting due to changes...

fs모듈을 통해 data/products.json파일을 변경하는 경우 nodemon에서 이를 인식하여 서버를 재시작 하는 것이었다.


✔️ 해결

해결방안 1) shell에서 옵션 넣기

위 로그를 통해 nodemon로컬 파일 변경을 인식해 서버를 재시작 하는 것이 원인이라 생각되어 nodemon restart due to change socket hang up이라고 구글에 검색을 해보았고 stackoverflow에서 해당 답변을 찾았다.

답변 링크

Are you using nodemon, or some other file-watcher? In my case, I was generating some local files, uploading them, then sending the URL back to my user. Unfortunately nodemon would see the "changes" to the project, and trigger a restart before a response was sent. I ignored the build directories from my file-watcher and solved this issue.

Here is the Nodemon readme on ignoring files: https://github.com/remy/nodemon#ignoring-files

답변 하단에 나온 링크로 들어가 nodemon에서 파일을 ignoring하는 방법을 찾았다.

nodemon --ignore 경로

해결방안 2) package.json에 설정하기

나는 package.json에서 설정해두고 npm start로 편하게 실행하고 싶어서 해당 링크 상단에서 찾은 방법을 사용하려고 한다.

nodemon의 ignore를 package.json에서 설정하는 방법
package.jsonnodemonConfig를 추가하여 nodemon에 관한 세부 설정이 가능했다.

아래는 해당 내용을 참고한 package.json의 일부다. 하단 ...은 생략

{
  "name": "learn-node",
  "version": "1.0.0",
  "description": "Complete Node.js Guide",
  "main": "app.js",
  "nodemonConfig": { // 추가한 부분! json은 주석이 불가능하다. 여기선 편의를 위해 추가했다.
    "ignore": [
      "data/*"
    ]
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon app.js"
  },
  ... 

💡 정리

  • nodemon은 로컬 파일이 변경되면 이를 인지하고 서버를 재시작. 이때 redirect를 한다면 socket hang up 오류 발생
  • ignore 옵션을 통해 불필요한 재시작 방지

이제 터미널에서 npm start를 통해 nodemon을 실행해도 socket hang up오류가 발생하지 않는다. 👍

profile
컴퓨터공학과 학부생

0개의 댓글