반응형

아래는 이 글의 동영상 강의입니다.

https://youtu.be/5FiFW_057KU

 

 

서버를 운영하다보면 정기적으로 Job을 실행해야 하는 경우가 생깁니다.

이럴때 정기적으로 Job을 자동으로 실행해 주는 것을 스케줄러라고 합니다.

 

nodejs에서는 node-shedule이라는 패키지를 사용하면 스케줄러를 쉽게 만들 수 있습니다.

node express 에서 scheduler를 만드는 방법을 알아 보겠습니다.

 

우선 node 프로젝트를 생성합니다.

node init -y

프로젝트에 express를 추가합니다.

npm i express

app.js 파일을 만들고 다음 내용을 추가합니다.

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

app.get('/', function (req, res) {
  res.send('Hello World')
})

app.listen(3000)

서버를 실행합니다.

node app

브라우저 주소창에 http://localhost:3000을 입력하고 "Hello World"가 나오는지 확인 합니다.

 

스케줄러를 만들기 위해 사용할 패키지를 다음 url에서 확인합니다.

https://github.com/node-schedule/node-schedule

 

GitHub - node-schedule/node-schedule: A cron-like and not-cron-like job scheduler for Node.

A cron-like and not-cron-like job scheduler for Node. - GitHub - node-schedule/node-schedule: A cron-like and not-cron-like job scheduler for Node.

github.com

 

프로젝트에 node-schedule을 설치합니다.

npm i node-schedule

app.js에 다음 내용을 추가합니다.

const schedule = require('node-schedule');
const express = require('express');
const app = express();

app.get('/', function (req, res) {
  res.send('Hello World');
})

app.listen(3000, function(){
    console.log('Express start on port 3000!');
    schedule.scheduleJob('* * * * * *', function(){
        console.log('The answer to life, the universe, and everything!');
    });
});

프로그램을 실행합니다.

node app

실행 결과는 다음과 같습니다.

스케쥴일 1초 마다 수행되는 것을 확인할 수 있습니다.

 

스케줄을 설정하는 법은 다음과 같습니다.

*    *    *    *    *    *
┬    ┬    ┬    ┬    ┬    ┬
│    │    │    │    │    │
│    │    │    │    │    └ day of week (0 - 7) (0 or 7 is Sun)
│    │    │    │    └───── month (1 - 12)
│    │    │    └────────── day of month (1 - 31)
│    │    └─────────────── hour (0 - 23)
│    └──────────────────── minute (0 - 59)
└───────────────────────── second (0 - 59, OPTIONAL)

앞에서 부터 초, 분, 시, 일, 월, 요일의 순입니다.

지속적인 실행은 *를 사용하면됩니다.

특정 시간에 실행하는 것은 아래와 같이 작성하면됩니다.

  • 매초 실행 : * * * * * *
  • 매분 실행 : * * * * *
  • 매분 0초에 실행 : 0 * * * * *
  • 매분 10초에 실행 : 10 * * * * *
  • 매시 1분 10초에 실행 : 10 1 * * * * 

다음은 매분 0초에 실행하도록 변경한 예입니다.

app.listen(3000, function(){
    console.log('Express start on port 3000!');
    schedule.scheduleJob('0 * * * * *', function(){
        console.log(new Date() + ' scheduler running!');
    });
});

실행 결과는 다음과 같습니다.

이상으로  Express에서 스케줄러를 만드는 방법이었습니다.

반응형
반응형

이 글의 동영상 강의 입니다.

https://youtu.be/wb4qGjfocwI

 

Express에서 라우팅을 별도의 파일로 분리할 수 있습니다.

 

한개의 파일로 분리하는 경우

  • 다음과 같이 router.js 파일을 만듭니다.
const express = require('express');
var router = express.Router();

router.get('/', function (req, res) {
  res.send('Express Server!');
});

module.exports = router;
  • index.js 파일에서 router.js를 사용하도록 코드를 추가합니다.
const express = require('express');
const app = express();
 
app.listen(3000);

app.use(require('./router'));

 

여러개의 파일로 분리하는 경우

  • user-router.js 파일을 만들고 다음 코드를 추가합니다.
const express = require('express');
var router = express.Router();

router.get('/', function (req, res) {
  res.send('This is user-router!');
});

module.exports = router;
  • board-router.js 파일을 만들고 다음 코드를 추가합니다.
const express = require('express');
var router = express.Router();

router.get('/', function (req, res) {
  res.send('This is board-router!');
});

module.exports = router;
  • index.js를 다음과 같이 수정합니다.
const express = require('express');
const app = express();
 
app.listen(3000);

app.use('/', require('./router'));
app.use('/user', require('./user-router'));
app.use('/board', require('./board-router'));

 

반응형
반응형

아래는 이 글의 동영상 강의입니다.

https://youtu.be/ceNqxXQMuKw

 

* 본 문서는 아래 사이트를 참고하여 작성하였습니다.
https://expressjs.com/ko/guide/using-middleware.html

 

Express 미들웨어 사용

미들웨어 사용 Express는 자체적인 최소한의 기능을 갖춘 라우팅 및 미들웨어 웹 프레임워크이며, Express 애플리케이션은 기본적으로 일련의 미들웨어 함수 호출입니다. 미들웨어 함수는 요청 오

expressjs.com

 

Express는 client의 요청을 받아 처리할때 미들웨어라는 개념을 사용합니다.

Express 애플리케이션은 기본적으로 일련의 미들웨어 함수 호출입니다.

 

Express에는 다음과 같은 유형의 미들웨어가 있습니다.

  • 애플리케이션 레벨 미들웨어
  • 라우터 레벨 미들웨어
  • 오류 처리 미들웨어
  • 기본 제공 미들웨어
  • 써드파티 미들웨어

 

애플리케이션 레벨 미들웨어

  • 애플리케이션 미들웨어는 다음과 같이 사용할 수 있습니다.
  • app.use(미들웨어);
  • app.use(미들웨어1, 미들웨어2...);
  • app.use에서 선언된 function이 미들웨어 입니다.
const express = require('express');
const app = express();
app.listen(3000);

app.use(function(req, res){
  res.send('Express Server!!!');
});
  • 한개의 요청을 여러개의 미들웨어가 처리할 수 있습니다.
    • 요청 경로(path)가 포함되지 않은 요청은 항상 실행됩니다.
    • function에서 next 인자를 처리하면 하위 스택을 처리하게 됩니다.
app.use(function (req, res, next) {
  console.log('Time:', Date.now());
  next();
});
  • client의 요청 경로(path)가 포함된 경우는 다음과 같이 처리합니다.
    • app.use(path, 미들웨어함수);
app.use('/user/:id', function (req, res, next) {
  console.log('Request Type:', req.method);
  next();
});
  • 다음은 라우트를 사용하는 방법입니다.
    라우트는 client의 요청을 http method별로 처리할 수 있습니다.
    • app.메소드(path, 미들웨어);
app.get('/user/:id', function (req, res, next) {
  res.send('USER');
});
  • next를 사용해서 미들웨어를 여러개 실행할 수도 있습니다.
app.use('/user/:id', function(req, res, next) {
  console.log('Request URL:', req.originalUrl);
  next();
}, function (req, res, next) {
  console.log('Request Type:', req.method);
  next();
});
  • 라우트 핸들러는 하나의 경로에 여러개의 라우트를 정의할 수 있습니다. 하지만 동일한 메소드를 2개 이상 만들고 앞에서 response를 처리하면 다음 메소드는 실행되지 않습니다.
app.get('/user/:id', function (req, res, next) {
  console.log('ID:', req.params.id);
  next();
}, function (req, res, next) {
  res.send('User Info');
});

// handler for the /user/:id path, which prints the user ID
app.get('/user/:id', function (req, res, next) {
  res.end(req.params.id);
});

 

라우터레벨 미들웨어

  • express.Router()를 사용하면 라우터 레벨의 미들웨어를 사용할 수 있습니다.
var app = express();
var router = express.Router();
  • 위 선언으로 라우터레벨 미들웨어를 다음과 같이 사용할 수 있습니다.
    라우터에서도 use와 method를 사용합니다.
// a middleware function with no mount path. This code is executed for every request to the router
router.use(function (req, res, next) {
  console.log('Time:', Date.now());
  next();
});

// a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path
router.use('/user/:id', function(req, res, next) {
  console.log('Request URL:', req.originalUrl);
  next();
}, function (req, res, next) {
  console.log('Request Type:', req.method);
  next();
});

// a middleware sub-stack that handles GET requests to the /user/:id path
router.get('/user/:id', function (req, res, next) {
  // if the user ID is 0, skip to the next router
  if (req.params.id == 0) next('route');
  // otherwise pass control to the next middleware function in this stack
  else next(); //
}, function (req, res, next) {
  // render a regular page
  res.render('regular');
});

// handler for the /user/:id path, which renders a special page
router.get('/user/:id', function (req, res, next) {
  console.log(req.params.id);
  res.render('special');
});

// mount the router on the app
app.use('/', router);

 

오류 처리 미들웨어

  • 오류 처리 미들웨어는 function의 parameter 첫번째 인자로 error를 받아 처리합니다.
app.use(function(err, req, res, next) {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

 

기본 제공 미들웨어

  • express에서 기본적으로 제공하는 미들웨어가 있습니다.
  • 다음은 기본제공 미들웨어 중 정적 모듈을 처리하는 static 미들웨어의 예제입니다.
app.use(express.static(__dirname+'/public'))
  • static으로 html 처리
    • http://localhost:3000/index.html 로 요청이 올경우 /public/index.html을 찾아 응답하게 됩니다.
  • static으로 이미지 처리
    • http://localhost:3000/logo.png 로 요청이 올경우 /public/logo.png를 찾아 응답하게 됩니다.
  • index.html 처리하기
    • http://localhost:3000 을 응답하는 코드는 다음과 같습니다.
app.get('/', function(req, res) {
  res.sendFile(__dirname+'/public/index.html')
});

 

써드 파티 미들웨어

  • express에서는 다양한 써드파티 미들웨어를 사용할 수 있습니다.
  • 필요한 기능에 따라 npm install을 사용하여 모듈을 설치하여 사용합니다.
  • 아래는 쿠키 구문 분석 미들웨어인 cookie-parser의 사용 방법 입니다.
  • 우선 cookie-parser 설치합니다.
npm install cookie-parser
  • 사용법은 다음과 같습니다.
var express = require('express');
var app = express();
var cookieParser = require('cookie-parser');

// load the cookie-parsing middleware
app.use(cookieParser());
  • 써드파티 미들웨어는 다음 링크에서 확인할 수 있습니다.

https://expressjs.com/ko/resources/middleware.html

 

Express 미들웨어

Express 미들웨어 목록에 적힌 Express 미들웨어 모듈들은 Expressjs 팀이 유지보수합니다. 미들웨어 모듈 설명 내장 함수 (Express 3) body-parser HTTP 요청 body를 파싱합니다. body, co-body, 그리고 raw-body도 참

expressjs.com

 

이상으로 express의 미들웨어에 대해 알아보았습니다.

반응형
반응형

NodeJS의 내부모듈인 http module을 사용해서 서버를 만들때 복잡하고 불편한 점들이 있습니다.

이를 개선한 NodeJS의 확장모듈인 express를 사용하는 방법을 알아봅니다.

 

다음은 이 글의 동영상 강의입니다.

https://youtu.be/Ej-N6c9JCbY

 

Express의 특징

  • Express는 모바일 및 웹용 애플리케이션 제작을 위한 일련의 기능을 제공하는 프레임워크입니다.
  • Express는 수많은 HTTP 유틸리티 메소드와 미들웨어를 통해 쉽고 빠르게 강력한 API를 제작할 수 있습니다.
  • Express는 빠른 성능을 제공합니다.
  • 많은 NodeJS 프레임워크들이 Express를 기반으로 하고 있습니다.

참조 : https://expressjs.com/ko

 

Express - Node.js 웹 애플리케이션 프레임워크

Node.js를 위한 빠르고 개방적인 간결한 웹 프레임워크 $ npm install express --save

expressjs.com

 

 

프로젝트 만들기

  • 프로젝트 폴더를 생성한 후 visual studio code를 실행합니다.
  • vscode의 메뉴에서 파일-폴더열기를 선택한 후 프로젝트폴더를 선택합니다.
  • 메뉴 터미널-새터미널을 선택한 후 다음을 입력하여 Nodejs프로젝트를 생성합니다.
npm init -y

 

express 설치

  • 우선 express 설치를 위해 npmjs.com에서 express를 검색합니다.
    리스트 중 제일 상단의 express (작성자:dougwilson)를 선택합니다.

npmjs.com

  • express의 설치 방법 사용예제 등을 확인합니다.

 

  • visual studio code의 터미널에서 다음 코드를 이용하여 expres를 설치합니다.
npm i express

 

프로그램 개발

  • vscode에서 index.js파일을 만들고 express 예제 코드를 아래와 같이 입력합니다.
const express = require('express')
const app = express()
 
app.get('/', function (req, res) {
  res.send('Hello World')
})
 
app.listen(3000)

 

서버 실행 및 확인

  • vscode의 터미널에서 다음 코드를 입력합니다.
node index
  • 브라우저를 실행하고 주소창에 다음 url을 입력합니다.
http://localhost:3000
  • 브라우저 결과는 다음과 같습니다.

이상으로 express의 설치와 실행방법에 대해 알아보았습니다.

반응형
반응형

이 글의 동영상 강의 1편입니다.

https://youtu.be/560LIgIiU8g

다음은 동영상 강의 2편입니다.

https://youtu.be/LoZhQXs85r8

 

이 글은 NodeJS 공식 홈페이지의 다음 글을 참고하여 작성하였습니다.

https://nodejs.org/ko/docs/guides/anatomy-of-an-http-transaction/

 

HTTP 트랜잭션 해부 | Node.js

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.

nodejs.org

 

NodeJS로 서버를 개발하려고 하려면 HTTP의 처리 과정을 이해하여야 합니다.

NodeJS에서 제공하는 http 모듈의 사용법과 같이 배워보도록 하겠습니다.

 

웹서버 만들기

  • 우선 웹서버 객체를 만듭니다.
const http = require('http');

const server = http.createServer((request, response) => {
});
  • 이때 사용된 createServer는 server 객체를 생성하고 발생한 이벤트를 전달하는 역할을 하므로 다음과 같이 변경할 수 있습니다.
const server = http.createServer();
server.listen(8080);
server.on('listening', () => {
   console.log(`listen on 8080 !!!`);
});

 

Request 처리하기

  • 생성한 서버에서 request를 받아 처리할 수 있습니다.
server.on('request', (request, response) => {
   console.log(request.headers);
   response.write('<h1>Node Server</h1>');
   response.end();
});
  • request에는 url, method, header 등의 정보가 포함됩니다.
server.on('request', (request, response) => {
  const { headers, method, url } = request;
  const userAgent = headers['user-agent'];
  console.log(`method : ${method}`);
  console.log(`url : ${url }`);
  console.log(`userAgent : ${userAgent}`);

  response.write('<h1>Node Server</h1>');
  response.end();
});
  • post나 put의 request에서 stream으로 전달되는 data와 end를 이용하면 body를 읽어올 수 있습니다.
  let body = [];
  request.on('error', (err) => {
    console.error(err);
  }).on('data', (chunk) => {
    body.push(chunk);
  }).on('end', () => {
    body = Buffer.concat(body).toString();
    console.log(body);

    response.write('<h1>Node Server</h1>');
    response.end();
  });
  • 테스트를 위해서 postman에서 다음과 같이 변경 합니다.
    • request method를 GET에서 POST로 바꿉니다.
    • headers에 다음 값을 추가합니다.
      • Content-Type: application/json

  • Body탭에서 다음 항목을 변경합니다.
    • body type을 none에서 raw로 변경합니다.
    • data type을 JSON으로 변경합니다.

  • Send를 클릭하면 다음과 같은 결과를 확인할 수 있습니다.

  • request에서 error 이벤트를 받아 오류를 처리할 수 있습니다.
request.on('error', (err) => {
  // 여기서 `stderr`에 오류 메시지와 스택 트레이스를 출력합니다.
  console.error(err.stack);
});

 

Response 사용하기

  • statusCode를 이용해 상태 코드를 전달할 수 있습니다.
    지정하지 않을 경우의 상태코드는 항상 200입니다.
response.statusCode = 404; // 클라이언트에게 리소스를 찾을 수 없다고 알려줍니다.
  • setHeader를 이용해 header를 설정할 수 있습니다.
response.setHeader('Content-Type', 'application/json');
response.setHeader('X-Powered-By', 'bacon');
  • 아래와 같이 명시적으로 header를 정의 할 수 있습니다.
response.writeHead(200, {
  'Content-Type': 'application/json',
  'X-Powered-By': 'bacon'
});
  • write와 end를 이용해 response body를 만들 수 있습니다.
response.write('<html>');
response.write('<body>');
response.write('<h1>Hello, World!</h1>');
response.write('</body>');
response.write('</html>');
response.end();
// 또는
response.end('<html><body><h1>Hello, World!</h1></body></html>');
  • respone에서 error event는 다음과 같이 처리할 수 있습니다.
response.on('error', (err) => {
  console.error(err);
});
  • 지금 까지의 내용을 정리하면 다음과 같이 코드를 작성할 수 있습니다.
const http = require('http');

http.createServer((request, response) => {
  const { headers, method, url } = request;
  let body = [];
  request.on('error', (err) => {
    console.error(err);
  }).on('data', (chunk) => {
    body.push(chunk);
  }).on('end', () => {
    body = Buffer.concat(body).toString();

    response.on('error', (err) => {
      console.error(err);
    });

    response.writeHead(200, {'Content-Type': 'application/json'})
    const responseBody = { headers, method, url, body };
    response.end(JSON.stringify(responseBody))
  });
}).listen(8080);

에코 서버 만들기

  • 다음과 같이 /echo로 요청하는 post 메소드에 대해서 응답하는 서버를 만들 수 있습니다.
const http = require('http');

http.createServer((request, response) => {
  request.on('error', (err) => {
    console.error(err);
    response.statusCode = 400;
    response.end();
  });
  response.on('error', (err) => {
    console.error(err);
  });
  if (request.method === 'POST' && request.url === '/echo') {
    request.pipe(response);
  } else {
    response.statusCode = 404;
    response.end();
  }
}).listen(8080);

이상으로 nodejs의 http 요청을 처리하는 기본적인 방법에 대해 알아보았습니다.

 

반응형
반응형

이 글의 동영상 강의

https://youtu.be/eTsgL0tPhy4

 

다음 시간부터는 NodeJS 서버개발에 대해 배울 예정입니다.

서버개발시 테스트를 위해서는 frontend 개발이 필요합니다.

이때 frontend 개발 없이 서버를 테스트 할 수 있는 tool들을 사용하게 되는데,

그 중에서 가장 많이 사용하는 Postman을 설치하고 테스트 해보겠습니다.

 

postman

Postman 설치

  • 구글에서 postman을 조회합니다.

postman

  • 첫번째 조회된 postman.com 사이트를 클릭합니다.
    첫 페이지의 Download the desktop app에서 자신의 OS에 맞춰 다운로드하고 설치를 진행합니다.

postman download

  • 설치가 완료되면 아래와 같이 postman이 실행됩니다.

postman desktop app

테스트용 Nodejs 서버 만들기

  • nodejs 프로젝트를 만들고 index.js에 다음 코드를 작성합니다.
const http = require('http');

http.createServer((request, response) => {
  response.write("<h1>NodeJS Test Server!</h1>");
  response.end();
}).listen(8080);
  • 다음 명령으로 서버를 start합니다.
node index

Postman으로 요청하기

  • postman 첫화면에서 "+" 탭을 클릭해서 새로운 요청을 만듭니다.

new request

  • "http://localhost:8080"으로 요청을 작성하고 Send 버튼을 클릭합니다.
    body에 아래와 같이 결과값이 나오면 정상적으로 요청이 처리된 것입니다.

  • 아래 Response Body 에서 "Preview" 탭을 클릭하면 브라우저의 결과를 볼 수 있습니다.

이상으로 postman을 이용해서 nodejs의 서버를 테스트하는 방법을 확인해 보았습니다.

 

다음 시간에는 nodejs의 http에 대해 자세히 알아보고,

테스트를 할때 postman의 다양한 사용법에 대해서도 알아보도록 하겠습니다.

 

반응형
반응형

nodejs와 mysql을 연동하는 법을 알아보겠습니다.

 

이글의 동영상 강의는 아래 링크를 클릭해주세요.

https://youtu.be/QssKt2efX40

 

MySQL Data 준비

  • Dababase 정보는 다음과 같습니다.
    • Schema : test
    • 사용자명 : test
    • 패스워드 : test
    • 테이블명 : user
  • 생성 쿼리는 다음과 같습니다.
# 스키마 생성
CREATE SCHEMA test;

# 사용자 생성 및 권한 추가
CREATE USER 'test'@'localhost' identified with mysql_native_password by 'test';
GRANT ALL PRIVILEGES ON test.* TO 'test'@'localhost';
flush privileges;

# 테이블 생성
CREATE TABLE IF NOT EXISTS `test`.`user` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `userid` VARCHAR(50) NULL,
  `username` VARCHAR(50) NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

# 테스트 데이터 입력
insert into test.user(userid, username) values ('codegear', '코드기어');
insert into test.user(userid, username) values ('ironman', '아이언맨');
insert into test.user(userid, username) values ('spiderman', '스파이더맨');

MySQL 설치와 스키마, 사용자, 테이블 생성은 아래 글을 참고하세요.

 

MySQL 설치하기

Windows에 MySQL을 설치하는 방법입니다. 이 글의 동영상 강의입니다. https://youtu.be/yZtub4AbbAo mysql download 구글에서 mysql download for windows로 검색합니다. 검색 결과창에서 "Download MySQL Comm..

codegear.tistory.com

 

MySQL-Schema, User, Table 생성하기

이 글의 동영상 강의입니다. https://youtu.be/hOOiqk8Z1gQ MySQL Workbench를 이용하여 가장 기본적인 Schema와 User를 생성하고, User에게 Schema의 권한을 주는법과, Schema에 Table을 생성하는 법을 알아보겠..

codegear.tistory.com

  • workbench를 실행하고 다음 쿼리를 실행합니다.
select * from user;
  • 실행 결과는 다음과 같습니다.

 

Nodejs 프로젝트 만들기

  • 프로젝트 폴더를 생성합니다.
  • VSCode를 실행하고 메뉴-폴더열기에서 프로젝트 폴더를 선택합니다.

  • 메뉴-터미널을 실행하고 다음 명령을 실행합니다.
npm init -y

 

MySQL 패키지 설치

  • www.npmjs.com에서 mysql을 검색합니다.

npmjs.com

  • 검색된 결과중 mysql exact match를 선택합니다.
  • 설치 방법과 사용법을 확인합니다.

npm install mysql

 

introduction

  • npm i mysql을 실행합니다.

npm i mysql

 

NodeJS + MySQL 연동 하기

  • index.js 파일을 만들고 다음 indroduction의 내용을 복사하여 붙여넣습니다.
var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'test',
  password : 'test',
  database : 'test'
});
 
connection.connect();
 
connection.query('SELECT * from USER', function (error, results, fields) {
  if (error) throw error;
  console.log('users: ', results);
});
 
connection.end();
  • 터미널에서 다음 명령으로 프로젝트를 실행합니다.
node index
  • 실행 결과는 다음과 같습니다.

 

반응형
반응형

이 글의 동영상 강의입니다.

https://youtu.be/sD7-xrF7XR4

 
NodeJS 프로젝트를 진행하다 보면 다음과 같은 상황들이 발생합니다.
A프로젝트는 노드 버전 12.13.0을 사용한다.
B프로젝트는 노드 버전 16.13.0을 사용한다.

 

즉, NodeJS 버전을 바꿔가면서 작업을 해야 하는 상황이 생기는 것입니다.

프로젝트를 변경할 때마다 NodeJS를 매번 새롭게 설치하기는 어렵습니다.

이때 NodeJS 버전을 쉽게 변경할 수 있는 툴이 NVM입니다.

 

NVM 설치하기

검색 사이트에서 NVM 또는 NVM windows를 검색하여 설치합니다.

https://github.com/coreybutler/nvm-windows

 

GitHub - coreybutler/nvm-windows: A node.js version management utility for Windows. Ironically written in Go.

A node.js version management utility for Windows. Ironically written in Go. - GitHub - coreybutler/nvm-windows: A node.js version management utility for Windows. Ironically written in Go.

github.com

 

 

설치가 완료되면 cmd 또는 powershell에서 다음 명령을 실행할 수 있습니다.

  • 설치된 NodeJS 목록 확인하기
nvm ls

  • nvm install을 사용해서 새로운 버전의 NodeJS 추가할 수 있습니다.
    nvm install {버전번호} (nodejs의 특정 버전 설치)
    nvm install latest (최신버전의 nodejs 설치)
    nvm install lts (nodejs LTS 버전 설치)
nvm install 12.13.0
nvm install 16.13.0
nvm install latest
nvm install lts
  • NodeJS 버전 변경하기
nvm use 12.13.0

 

윈도우용 NVM 오류 해결 방법

윈도우용 NVM을 사용하면 "Exit 5..." 라는 오류가 종종 나옵니다.

이때 cmd나 파워쉘을 관리자 권한으로 실행해서 nvm use를 사용하시면 됩니다.

 

그래도 안될때는 다음 방법을 사용하면 오류를 해결하실 수 있습니다.

  • NVM 위치 변경하기
nvm root D:\nodejs-root\nvm
  • NVM 기본 설치 위치에서 다음 파일들을 복사해서 새로운 NVM 폴더에 넣어줍니다.
    기본 설치 위치 = C:\사용자\{사용자ID}\AppData\Roaming\nvm
elevate.cmd
elevate.vbs
  • CMD 또는 PowerShell을 관리자 권한으로 실행하고, nvm을 사용합니다.
nvm use 12.13.0

 

NVM을 사용하면 NodeJS의 버전을 손쉽게 변경하여 사용할 수 있습니다.

 

반응형
반응형

이 글의 동영상 강의입니다.

https://youtu.be/oHXHOzg9oxQ

 

이 글은 module에 대해 잘 정리되어 있는 아래 사이트를 참고해서 작성되었습니다.

nodejs의 module은 굉장히 중요한 개념입니다.

개발시에 module을 모르면 개발이 불가능하므로, 개념을 잘 이해하여야 합니다.

 

nodejs는 모듈 단위로 기능을 분리할 수 있습니다.

또한 분리된 기능을 조립하여 사용이 가능합니다.

 

nodejs module의 특징

nodejs의 module은

  • 업계표준인 CommonJS의 module 방식을 따르고 있습니다.
  • 파일과 1:1 대응 관계를 갖습니다.
  • 별도 scope을 갖기 때문에 전역 변수의 중복이 발생하지 않습니다.
  • module.exports 또는 exports를 통해 외부로 공개할 수 있습니다.
  • module.exports = exports 와 동일합니다.
  • require를 사용하여 외부에서 module을 사용 할 수 있습니다.
  • 변수(variable), 객체(object), 함수(function), 폴더(folder)를 module로 만들 수 있습니다.

변수를 사용한 예제

  • constants.js
module.exports = { 
    SEND_MAIN_PING: 'send_main_ping', 
};
 
  • index.js
const { SEND_MAIN_PING } =require('./constants')

console.log(SEND_MAIN_PING);

함수를 사용한 예제

  • sum.js
var sum = function(a,b){
    return a + ' + ' + b + ' = ' + a+b;
}

module.exports = sum;
  • index.js
const sum = require('./sum');

console.log(sum(1,10));

폴더를 사용한 예제

  • 폴더 구조는 다음과 같습니다.

폴더구조

  • module/index.js
module.exports = {
    sum: require('./sum'),
    minus: require('./minus')
}
  • index.js
const myModule = require('./module');

console.log(myModule.sum(1,10));

 

Core Module

nodejs에 기본적으로 포함되어 있는 module을 core module이라고 합니다.

core module은 require를 이용해 바로 사용할 수 있습니다.

const http = require('http');

 

외부 Module (NPM)

nodejs는 npm으로 설치한 외부 모듈을 사용할 수 있습니다.

따라서 npmjs.com에 배포되어 있는 모든 모듈을 자유롭게 이용할 수 있다는 장점이 있습니다.

  • npmjs.com에서 검색
    다음은 npmjs.com에서 nodejs의 서버 개발을 쉽게 해주는 express를 검색한 내용입니다.
    붉은색 박스에 보시면 설치법이 나와 있습니다.

  • npm으로 설치한 모듈도 동일하게 require를 통해 사용할 수 있습니다.
const express= require('express');

 

이상으로 nodejs의 module 사용법에 대해 알아보았습니다.

반응형
반응형

이 글의 동영상 강의

https://youtu.be/ZKSEA7DZ5x8

 

Nodejs를 설치하고 나면,
Nodejs를 실행할 수 있는 여러가지 방법이 있습니다.

 

1. Command Line에서 실행하기

2. Browser 개발자 도구에서 실행하기

3. 파일을 만들어 실행하기

 

하나씩 실행하는 법을 알아보겠습니다.

1. Command Line에서 실행하기

  • 윈도우 검색창에 CMD를 입력하고 실행합니다.

명령 프롬프트 실행\

  • 명령프롬프트에서 node를 입력 후 실행(Enter)합니다.

node 실행

  • 다음 내용을 입력합니다.
var msg = "Hello World!!!"
console.log(msg)
  • 실행 결과는 다음과 같습니다.

실행결과

2. Browser 개발자 도구에서 실행하기

  • 크롬브라우저를 실행합니다.
  • F12키를 눌러 개발자 도구를 실행합니다.
  • 콘솔 탭을 클릭하고 다음 내용을 입력합니다.
var msg = "Hello World!!!"
console.log(msg)
  • 실행 결과는 다음과 같습니다.

크롬 브라우저 개발자 도구

3. Javascript 파일을 만들어 실행하기

  • 앞에서 설명한 2가지 방법은 간단한 입력은 가능하지만, 복잡한 프로그램은 구현하기 어렵습니다.
  • Nodejs로 제대로 된 프로그램을 만들려면 Javascript 파일을 만들어 실행해야 합니다.
  • 편집기를 이용해 test.js 파일을 만듭니다. 저는 Visual Studio Code(VSCode)를 이용했습니다.
  • test.js에 다음 내용을 입력합니다.
function plus(a,b) {
    return a + b;
}

function minus(a,b) {
    return a - b;
}

console.log(plus(2,3));
console.log(minus(10,6));
  • VSCode의 메뉴에서 터미널-새터미널을 실행합니다.
  • node test를 입력하고 실행합니다.
  • 실행 결과는 다음과 같습니다.

이상으로 Nodejs를 실행하는 방법 3가지를 알아보았습니다.

 

반응형

+ Recent posts