Node JS 시작하기

shinee·2022년 6월 18일
0

NodeJS

목록 보기
1/6

1. npm init

node js를 설치하고자 하는 곳에서 npm init 명령어를 실행하면 아래와 같은 화면이 나온다.
package name만 입력해주고 나머지는 Enter를 쭉 눌러준다. (물론 다 입력해줘도 되겠지..)
그렇게 하면 package.json 파일이 생성된다.

2. express 설치

node js 의 대표적인 프레임워크인 express를 설치하여 서버를 실행해보자. 아래의 명령어를 실행하여 express를 설치한다.

npm install express --save


package.json 파일 내 express가 추가되었다!

3. index.js

디렉토리에 index.js 파일을 하나 만든다. 이 index.js 파일이 entry point가 된다.
index.js 파일 내 아래와 같이 입력해준다.
아래 코드는 요약하자면 express를 import 하고, port 5000번으로 서버를 실행하는 것이다. 이 서버는 '/' url get 요청을 보내면 "Start Velog!!" 라는 응답을 줄 것이다!

const express = require('express')
const app = express()
const port = 5000

app.get('/', (req, res) => {
    res.send('Start Velog!!')
})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

4. 서버 실행

다시 package.json 파일로 돌아가 scripts부분에 명령어를 하나 추가해보자!

"start": "node index.js"


그리고 터미널에서 아래의 명령어로 서버를 실행하고 localhost:5000번으로 접속하면..

npm run start

짜잔~~~ 잘 실행이 됐다 ㅎㅎ

References

profile
developer

0개의 댓글