node.js 검색 결과

6개 발견
  1. 미리보기
    2020.04.06 - mr.november11

    [node.js] AWS SDK사용하여 S3 버킷에 업로드하기

  2. 미리보기
    2019.03.04 - mr.november11

    [node.js] winston version 3기준 node.js 로깅 설정(local timestamp 적용)

  3. 미리보기
    2019.03.04 - mr.november11

    [node.js] node.js 로 생성한 스크립트를 서버 내 daemon 형태로 실행하기

  4. 미리보기
    2019.02.21 - mr.november11

    [node.js] node.js 로 REST API 구축하기 위해 필요한 모듈 리스트

  5. 미리보기
    2019.02.13 - mr.november11

    [node.js] docker 를 활용한 mongodb 실행 및 node.js 로 mongodb 연동하기

  6. 미리보기
    2018.09.24 - mr.november11

    [node.js]node.js 실행 시 events.js:183 throw er; // Unhandled 'error' event 에러가 발생한 경우

참고 사이트 : https://aws.amazon.com/ko/sdk-for-node-js/

예제 코드 

aws-sdk 라이브러리를 활용하여 파일 경로에 해당하는 파일을 s3 로 업로드한다. 

AceessKey 는 s3 upload 권한을 가져야 한다. 

const AWS = require('aws-sdk');
const fs = require('fs');
const path = require('path');

const accessKeyId = '<ACCESS_KEY>';
const secretAccessKey = '<SECRET_ACCESS_KEY>';
const region = 'ap-northeast-2';
const bucket = '<BUCKET_NAME>';
const s3 = new AWS.S3({accessKeyId, secretAccessKey, region});

const fileName = <FILE_NAME>;

const fileStream = fs.createReadStream(fileName);
fileStream.on('error', function(err) {
  console.log('File Error', err);
});

const uploadParams = {
  Bucket: bucket,
  Key: path.basename(fileName),
  Body: fileStream,
};

s3.upload(uploadParams, function(err, data) {
  if (err) {
    console.log('Error', err);
  }
  if (data) {
    console.log('Upload Success', data.Location);
  }
});

 

 

다른 카테고리의 글 목록

node.js 카테고리의 포스트를 톺아봅니다

[node.js] winston version 3기준 node.js 로깅 설정(local timestamp 적용)

설명

  • winston 은 node.js 에서 사용하는 대표적인 logging 모듈이다.

  • 기본 형태로 logging 시 timestamp 가 기록되지 않으며,

    Local time 으로 지역 시간대 적용을 위해서 별도의 format 정의가 필요하다.

  • 아래 코드 예제를 통해서 로깅 파일 생성 및 지역 시간(서울) 기준으로 로깅이 가능하다.

실행 코드

const winston = require('winston')

const moment = require('moment-timezone')

const { createLogger, format, transports } = require('winston');
const { combine, timestamp, label, printf } = format;

const myFormat = printf(({ level, message, label, timestamp }) => {
  return `${timestamp} [${label}] ${level}: ${message}`;
});

const appendTimestamp = format((info, opts) => {
  if(opts.tz)
    info.timestamp = moment().tz(opts.tz).format();
  return info;
});

// Config Log
const logger = winston.createLogger({
  format: combine(
      label({ label: 'gather_gluster_info' }),
      appendTimestamp({ tz: 'Asia/Seoul' }),
      myFormat
  ),
  defaultMeta: { service: 'user-service' },
  transports: [
    //
    // - Write to all logs with level `info` and below to `combined.log`
    // - Write all logs error (and below) to `error.log`.
    new winston.transports.File({ filename: 'test.log' })
  ]
});

logger.log('error', "TT")


다른 카테고리의 글 목록

node.js 카테고리의 포스트를 톺아봅니다

[node.js] node.js 로 생성한 스크립트를 서버 내 daemon 형태로 실행하기

1. 배경

  • node.js 로 실행한 코드를 콘솔로 접속하여 실행할 시 콘솔 접속 후에는 해당 프로그램이 종료된다.

  • cronjob 과 같은 배치성 프로그램을 daemon 형태로 지속 실행하기 위해서 forever 란 패키지를 이용해야한다.

2. 설치

  • npm으로 forever 패키지를 설치한다.

  • 서버 내 공용으로 사용될 예정으로 global 옵션인 -g 를 적용한다.

$ npm install -g forever

3. 사용 방법

  • forever command 를 이용하여 node.js 코드를 실행한다.

  • 사용 가능한 명령어는 help 를 참고 시 아래와 같다.

    $ forever -h
    help:   usage: forever [action] [options] SCRIPT [script-options]
    help:    
    help:   Monitors the script specified in the current process or as a daemon
    help:    
    help:   actions:
    help:     start               Start SCRIPT as a daemon
    help:     stop               Stop the daemon SCRIPT by Id|Uid|Pid|Index|Script
    help:     stopall             Stop all running forever scripts
    help:     restart             Restart the daemon SCRIPT
    help:     restartall         Restart all running forever scripts
    help:     list               List all running forever scripts
    help:     config             Lists all forever user configuration
    help:     set <key> <val>     Sets the specified forever config <key>
    help:     clear <key>         Clears the specified forever config <key>
    help:     logs               Lists log files for all forever processes
    help:     logs <script|index> Tails the logs for <script|index>
    help:     columns add <col>   Adds the specified column to the output in `forever list`
    help:     columns rm <col>   Removed the specified column from the output in `forever list`
    help:     columns set <cols> Set all columns for the output in `forever list`
    help:     columns reset       Resets all columns to defaults for the output in `forever list`
    help:     cleanlogs           [CAREFUL] Deletes all historical forever log files

  • 실행 명령어 : forever start test_code.js

  • 확인 명령어 : forever list

    $ forever list
    info:   Forever processes running
    data:       uid command       script                 forever pid   id logfile                 uptime      
    data:   [0] QFcD test_code.js 39801   39808   /root/.forever/QFcD.log 0:0:0:53.367
  • 실행중지 명령어 : forever stop test_code.js 또는 forever stopall



다른 카테고리의 글 목록

node.js 카테고리의 포스트를 톺아봅니다

[node.js] node.js 로 express 서버 구축 시 필요한 모듈 리스트

1. express

  • express 는 node.js 에서 web 서버 구축을 위해 꼭 필요한 모듈이다.

설치법

$ npm install express --save

사용법

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

app.get('/', (req, res) => {
  res.send("Hello World")
})

app.listen(3000, () => console.log("Listening on port 3000"))

2. nodemon

  • nodemon 은 node.js 코드가 변경될 때마다 web 서버를 자동으로 재시작 해준다.

  • 개발 편의성을 위해 꼭 필요하다.

설치법

$ npm install nodemon --save

사용법

  • node 대신에 nodemon 프로세스로 코드를 실행한다.

MacBook-Pro:express-demo server$ nodemon index.js
[nodemon] 1.18.9
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node index.js`
Listening on port 3000                         <====== 소스코드 수정 후 저장 시점에 web 서버가 재실행
[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
Listening on port 3000

3. joi

  • POST API 등으로 신규 값을 추가할 시 전달된 값의 유효성을 사전에 검사해야한다.

    ex> email 의 경우 @ 가 입력되어야 한다.

  • joi 는 입력된 값의 scheme 를 사전에 정의하여 값의 유효성을 검사 한다.

설치법

$ npm install joi --save

사용법

  1. 코드 상단에 joi 모듈 import

    const Joi = require('joi')
  2. post 함수 내 joi schema 및 validation 체크 함수를 입력한다.

    • 예시에서 전달될 값은 name 이라는 key 를 입력받으며, 3글자 이상 되어야 한다.

    • result 값으로 error 가 존재할 경우 res.status(400) 으로 400 Error 를 발생 시킨다.

    app.post('/api/courses', (req,res) => {
      const schema = {
          name : Joi.string().min(3).required()
      }

      result = Joi.validate(req.body, schema)
      console.log(result)

      if(result.error ){
          res.status(400).send(result.error)
          return
      }

      const course = {
          id : courses.length + 1,
          name : req.body.name
      }
      courses.push(course)
      res.send(course)
    })
  3. 유효하지 않은(3글자 미만) 값이 전달됐을 경우 result.error 에 의해 아래와 같이 출력된다.

    {
      "isJoi": true,
      "name": "ValidationError",
      "details": [
          {
              "message": "\"name\" length must be at least 3 characters long",
              "path": [
                  "name"
              ],
              "type": "string.min",
              "context": {
                  "limit": 3,
                  "value": "ch",
                  "key": "name",
                  "label": "name"
              }
          }
      ],
      "_object": {
          "name": "ch"
      }
    }

4. helmet

  • helmet 은 http header 의 보안 취약점을 보완해주는 middle ware 이다.

    • cspContent-Security-Policy 헤더를 설정하여 XSS(Cross-site scripting) 공격 및 기타 교차 사이트 인젝션을 예방합니다.

    • hidePoweredByX-Powered-By 헤더를 제거합니다.

    • hpkpPublic Key Pinning 헤더를 추가하여, 위조된 인증서를 이용한 중간자 공격을 방지합니다.

    • hsts는 서버에 대한 안전한(SSL/TLS를 통한 HTTP) 연결을 적용하는 Strict-Transport-Security 헤더를 설정합니다.

    • ieNoOpen은 IE8 이상에 대해 X-Download-Options를 설정합니다.

    • noCacheCache-Control 및 Pragma 헤더를 설정하여 클라이언트 측에서 캐싱을 사용하지 않도록 합니다.

    • noSniffX-Content-Type-Options 를 설정하여, 선언된 콘텐츠 유형으로부터 벗어난 응답에 대한 브라우저의 MIME 가로채기를 방지합니다.

    • frameguardX-Frame-Options 헤더를 설정하여 clickjacking에 대한 보호를 제공합니다.

    • xssFilterX-XSS-Protection을 설정하여 대부분의 최신 웹 브라우저에서 XSS(Cross-site scripting) 필터를 사용하도록 합니다.

설치법

$ npm install --save helmet

사용법

const Helmet = require('helmet')

app.use(Helmet)

5. morgan

  • morgan 은 express 내에서 로그 기록을 남겨주는 middleware 이다.

설치법

$ npm install --save morgan

사용법

const morgan = require('morgan')

app.use(morgan('short'))

실행 결과

Listening on port 3000
::1 - GET /api/courses/ HTTP/1.1 200 79 - 4.581 ms
::1 - GET /api/courses/ HTTP/1.1 200 79 - 0.564 ms
::1 - GET /api/courses/ HTTP/1.1 200 79 - 1.390 ms
::1 - GET /api/courses/ HTTP/1.1 200 79 - 0.227 ms

6. config

  • config 모듈은 application 에서 사용하는 설정 값을 공통된 파일을 통해 관리할 수 있도록 한다.

  • 시스템 환경 설정에 따라 default, development, production 등의 모드로 실행 가능하다.

설치법

$ npm install config --save

사용법

  • config 폴더 생성 후 default.json 파일 생성

    $ cat ./config/default.json
    {
      "name" : "My APP Configuration name"
    }
  • node.js 코드 내 아래와 같이 사용

    const config = require('config')

    console.log(config.get('name'))

실행 결과

My Gluster APP

7. winston

  • winston 은 node.js 의 대표적인 Logging 모듈이다.

  • winston 2.0 기준으로 정리 되어있다.

설치법

$ npm install winston --save

사용법

  • transports 설정을 통해 Console 및 File 에 로그 결과를 기록할 수 있다.

  • winston.log('로그 등급', '로그 metadata', '메시지') 형식으로 로그를 저장하면 된다.

var winston = require('winston');
winston.add(winston.transports.File, { filename: 'somefile.log' });
winston.log('info', 'Hello distributed log files!');
winston.info('Hello again distributed logs');

winston.level = 'debug';
winston.log('debug', 'Now my debug messages are written to console!');

winston.log('info', 'Test Log Message', { anything: 'This is metadata' });

실행 결과

  • somefile.log 내 아래와 같이 기록된다.

{"level":"info","message":"Hello distributed log files!","timestamp":"2019-02-21T02:53:30.870Z"}
{"level":"info","message":"Hello again distributed logs","timestamp":"2019-02-21T02:53:30.871Z"}
{"level":"debug","message":"Now my debug messages are written to console!","timestamp":"2019-02-21T02:53:30.871Z"}
{"level":"info","message":"Hello distributed log files!","timestamp":"2019-02-21T02:54:28.246Z"}
{"level":"info","message":"Hello again distributed logs","timestamp":"2019-02-21T02:54:28.247Z"}
{"level":"debug","message":"Now my debug messages are written to console!","timestamp":"2019-02-21T02:54:28.247Z"}
{"anything":"This is metadata","level":"info","message":"Test Log Message","timestamp":"2019-02-21T02:54:28.247Z"}


다른 카테고리의 글 목록

node.js 카테고리의 포스트를 톺아봅니다

[node.js] docker 를 활용한 mongodb 실행 및 node.js 로 mongodb 연동하기

1. Docker 로 mongodb 실행

1) docker-compose.yml 파일 생성

  • volumes 영역에는 외부에 별도로 저장한 db 데이터 경로를 지정한다.

version: '2'

services:
mongodb:
  image: 'bitnami/mongodb:3.6'
  ports:
    - "27017:27017"
  volumes:
    - /Users/db/data:/data/db

2) docker-compose 실행

  • 명령어 : docker-compose up

    $ docker-compose up
    Starting db_mongodb_1_ea510d3ef245 ... done
    Attaching to db_mongodb_1_ea510d3ef245

2. nodes.js 에서 mongodb 연동 후 CRUD(생성, 읽기, 수정, 삭제) 하기

1) mongoose 모듈 설치

  • node.js 에서 mongodb 를 활용하려면 mongoose 모듈 설치가 필요하다.

    npm install mongoose --save

2) mongoose 모듈 로드 및 연결

const mongoose = require('mongoose')

mongoose.connect('mongodb://localhost:27017/playgroud')
.then( () => console.log('Connected to MongoDB ... '))
.catch( err => console.error('Could not connect to MongoDB ... '))

3) Schema 및 Class, Obejct 정의 후 저장

  • node.js 에서 사용할 mongodb 데이터의 schema(형식) 을 정의한다.

    const courseSchema = new mongoose.Schema({
      name : String,
      author : String,
      tags : [ String ],
      date : { type: Date, default: Date.now },
      isPublished : Boolean
    })

    const Course = mongoose.model('Course', courseSchema)
    const course = new Course({
      name : "Node.js Course",
      author : "Mosh",
      tags : ['node', 'backend'],
      isPublished : true
    })
    const result = await course.save();


다른 카테고리의 글 목록

node.js 카테고리의 포스트를 톺아봅니다

node.js 실행 시 events.js:183 throw er; // Unhandled 'error' event 에러가 발생한 경우

1. 현상

node app.js 실행 시 events.js 에서 Unhandled 'error' event 에러 발생

 

2. 원인 및 해결방법

기존에 node app.js 프로세스가 기실행 중일 경우 port 충돌 발생으로 프로세스가 정상 실행되지 않는다.

해당 프로세스를 종료하면

에러 문구 없이 정상적으로 실행 가능하다.

 

다른 카테고리의 글 목록

node.js 카테고리의 포스트를 톺아봅니다