Language/Node.js

Node Snippets 명령어

JangKroed 2022. 10. 5. 12:18
728x90
반응형

 

 

NodeJS 스니펫 모음

 

 

 

node-express - 익스프레스 서버 생성

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

app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening on port ${port}!`))

 

node-express-get, GET 경로 생성

app.get('/', (req, res) => {
  res.send('GET request to the homepage')
})

 

node-express-get-params는 GET 경로를 생성하고 매개변수에 액세스하는 방법을 보여줍니다.

app.get('/books/:bookId', (req, res) => {
  res.send(req.params.bookId)
})


node-express-post, POST 경로 생성

app.post('/', function (req, res) {
  res.send('POST request to the homepage')
})


node-express-post-params는 POST 경로를 생성하고 본문에 액세스하는 방법을 보여줍니다.

var bodyParser = require('body-parser');
app.use(bodyParser.json());

app.post('/update', function(req, res) {
  const { name, description } = req.body;
  res.send(`Name ${name}, desc ${description}`);
});


node-express-post-params-alt, POST 경로 생성, 본문 액세스 방법, express 4.16 이상에서 작동

app.use(express.json())
app.listen(8080)

app.post('/test', (req, res) => {
  res.json({ body: req.body })
});

 

node-express-put-params는 PUT 경로를 생성하고 본문에 액세스하는 방법을 보여줍니다.

var bodyParser = require('body-parser');
app.use(bodyParser.json());

app.put('/products', function(req, res) {
  const { id, name, description } = req.body;
  res.send(`Name ${id} ${name}, desc ${description}`);
});


node-express-delete-params는 DELETE 경로를 생성하고 경로 매개변수에 액세스하는 방법을 보여줍니다.

var bodyParser = require('body-parser');
app.use(bodyParser.json());

app.delete('/products/:id', function(req, res) {
  const { id } = req.params;
  res.send(`Delete record with id ${id}`);
});


node-express-query-params는 POST 경로를 생성하고 쿼리 매개변수에 액세스하는 방법을 보여줍니다.

var bodyParser = require('body-parser');
app.use(bodyParser.json());

// for routes looking like this `/products?page=1&pageSize=50`
app.get('/products', function(req, res) {
  const page = req.query.page;
  const pageSize = req.query.pageSize;
  res.send(`Filter with parameters ${page} and ${pageSize}`)
})


node-express-middleware-logger, 예제 미들웨어 생성

const logger = function (req, res, next) {
  console.log('logging')
  next()
}

app.use(logger)

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


node-express-middleware-error, 오류 처리 미들웨어 생성

app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(500).send('Something broke!')
});

 

node-http-server, 간단한 HTTP 서버 생성

var http = require('http');
http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello World');
}).listen(8081);

console.log('Server running at http://127.0.0.1:8081/');


node-file-read-sync, 동기적으로 파일을 읽습니다.

var fs = require('fs');
var data = fs.readFileSync('file.txt');


node-file-read-async, 콜백으로 파일을 비동기적으로 읽습니다.

var fs = require('fs');
fs.readFile('input.txt', function (err, data) {
  if (err) return console.error(err);
  console.log(data.toString());
});


node-event-emitter, 이벤트 이미터 생성, 이벤트 발생 및 해당 이벤트 구독 표시

var events = require('events');
var eventEmitter = new events.EventEmitter();
eventEmitter.emit('my_event');
eventEmitter.on('my_event', () => {
  console.log('data received successfully.');
});

 

node-promise-create, Promise 생성

new Promise((resolve, reject) => {
  let condition = false;
  if(condition) {
    resolve('data')
  } else {
    reject('error')
}
})


node-promise-shorthand, 정적 메서드 resolve() 및 reject()를 사용하여 약속을 만듭니다.

const promiseThatWillResolve = Promise.resolve('data');
const promiseThatWillReject = Promise.reject('error');


node-promise-all, Promise.all([]) 메서드를 사용하여 약속 목록을 확인합니다.

const getData = () => Promise.resolve('data');
const getMoreData = () => Promise.resolve('more data');

Promise.all(
  getData(),
  getMoreData()
).then(result => {
  const [data, moreData] = result;
})


node-async-await, async/await 사용

async function getData() {
  return Promise.resolve('data');
}

async function getMoreData(data) {
  return Promise.resolve(data + 'more data');
}

async function getAll() {
  const data = await getData();
  const moreData = await getMoreData(data);
  return `All the data: ${data}, ${moreData}`;
}

getAll().then((all) => {
  console.log('all the data')
})


node-express-schema-validation, adding schema validation for express, read more about the usage of schema validation with Joi at https://github.com/hapijs/joi

(node-express-schema-validation, express에 대한 스키마 유효성 검사 추가, https://github.com/hapijs/joi에서 Joi를 사용한 스키마 유효성 검사 사용에 대해 자세히 읽어보세요.)

 

GitHub - hapijs/joi: The most powerful data validation library for JS

The most powerful data validation library for JS. Contribute to hapijs/joi development by creating an account on GitHub.

github.com

const Joi = require('joi');
const loginSchema = Joi.object().keys({
  username: Joi.string()
    .min(3),
    .max(10),
    .required(),
  password: Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/)
});

app.post('/login', function(req, res) {
  const valid = Joi.validate(req.body, loginSchema).error === null;
  if (!valid) {
    res.status(422).json({
      status: 'error'
      message: 'Invalid request data'
      data: req.body
    });
  } else {
    // happy days - login user
    res.send(`ok`);
  }
});


node-regex-test-digits는 문자열이 숫자의 정규식과 일치하는지 여부를 테스트하는 test() 메서드를 호출합니다.

const isMatch = /\d+/.test('abc123')


node-regex-test-word는 문자열이 단어 경계의 정규식과 일치하는지 여부를 테스트하는 test() 메서드를 호출합니다.

const isMatch = /\w+/.test('abc123')


node-regex-match, 정규식에서 match() 메서드를 호출하여 파일 확장자를 찾습니다.

const [, extension] = 'file.txt'.match(/\.(\w+)/)


node-regex-match-named-group은 정규식에서 match() 메서드를 호출하고 이를 확장이라는 그룹에 배치합니다.

const { groups: { extension } } = 'file.txt'.match(/\.(?<extension>\w+)/)


node-http-quark, 프레임워크 quarkhttp를 사용하여 HTTP 앱을 생성합니다.

const quark = require('quarkhttp');
const app = quark();
app.get('/', (req, res) => res.send('hello world'))
app.listen(3000, () => {
  console.log('Server running on 3000');
})


node-http-quark-get, quarkhttp 앱에 GET 경로 추가

app.get('/products', (req, res) => res.json([{ id: 1, name: 'a product' }]))


node-http-quark-post, quarkhttp 앱에 POST 경로 추가

app.post('/products', (req,res) => {
  console.info('body', req.body)
  res.json(req.body);
})


node-http-quark-put, quarkhttp 앱에 PUT 경로 추가

app.put('/products', (req,res) => {
  console.info('body', req.body)
  res.json(req.body);
})


node-http-quark-middleware, quarkhttp 앱에 미들웨어 추가

app.get('/orders', (req, res, next) => {
  if (req.headers['authorization'] === 'abc123') {
    next()
  } else {
    res.statusCode = 401;
    res.send('Not allowed')
  }
}, (req, res) => {
  res.send('Protected route');
})


node-jest-suite, 테스트 스위트 추가

describe('', () => {
  
})

 

node-jest-test, 테스트 추가

test('', () => {})

 

node-jest-test-expect, 예상 테스트를 추가합니다.

test('', () => {
  expect(1).toBe(2)
})

 

node-jest-expect, toBe()를 사용하여 기대를 추가합니다.

 expect(1).toBe(2)

 

 

node-jest-expect-to-equal, toEqual()을 사용하여 기대를 추가합니다.

let obj = { a: '1' }
expect(obj).toEqual({ a: '1' })


node-jest-test-expect-to-equal, toEqual()을 사용하여 예상 테스트를 추가합니다.

test('', () => {
  let obj = { a: '1' }
  expect(obj).toEqual({ a: '1' })
})


node-jest-expect-to-throw, toThrow()를 사용하여 기대치를 추가합니다.

const thisThrows = () => throw new Error('error message')
expect(thisThrows).toThrow('error message')


node-jest-test-expect-to-throw, toThrow()를 사용하여 예상 테스트를 추가합니다.

test('', () => {
  const thisThrows = () => throw new Error('error message')
  expect(thisThrows).toThrow('error message')
})


node-jest-test-beforeAll, beforeAll() 추가, 이 메서드는 모든 테스트 전에 실행

  beforeAll(() => {
    
  })


node-jest-test-afterAll, afterAll() 추가, 이 메서드는 모든 테스트 후에 실행

  afterAll(() => {
    
  })


node-supertest-init는 supertest와 테스트하려는 앱에 대한 초기 가져오기를 추가합니다. 테스트하려는 앱이 다음과 같다고 가정합니다.

const supertest = require('supertest')
const app = require('../app');
const server = app.listen(3000, () => {
  console.log('listening at port 3000')
})
let request;


//  app.js
const express = require('express')
const app = express();
// your route definitions - // 경로 정의
module.exports = app;

파일 구조는 다음과 같습니다.

-| app.js    // 웹 앱이 가는 곳
-| __tests__/
---| app.js  // 테스트가 진행되는 곳



node-supertest-beforeall, 앱 인스턴스를 사용하도록 supertest를 구성합니다. 

이는 supertest를 초기화하는 데 필요한 단계입니다.

beforeAll(() => {
  request = supertest(app)
})


node-supertest-aftereall은 테스트 실행 후 웹 앱이 종료되도록 하는 데 필요한 단계입니다.

afterAll(async(close) => {
  server.close(() => {
    close()
   console.log('server closed');
  })
})


node-supertest-testget, GET route를 테스트하는 수퍼 테스트의 예

test('testing a GET route', async () => {
  let products = [
  {
    id: 1,
    name: 'book'
  },
  {
    id: 2,
    name: 'book2'
  }
 ];

  const res = await request.get('/products');
  expect(res.status).toBe(200);
  expect(res.body).toEqual(products);
})


node-supertest-testgetwithparam, 경로 매개변수로 GET 경로를 테스트하는 수퍼테스트의 예

test('testing a GET route with router param', async () => {
  let product = {
    id: 1,
    name: 'book'
  };
  const res = await request.get('/products/1');
  expect(res.status).toBe(200);
  expect(res.body).toEqual(product);
});

 

node-supertest-testpost, 페이로드로 POST 경로를 테스트하는 수퍼 테스트의 예

test('testing a POST route with a payload', async () => {
  let product = {
    name: 'book3'
  };
  const res = await request
  .post('/products')
  .send(product);
  expect(res.status).toBe(200);
  expect(res.body).toEqual({ id: 3, ...product});

  const newRes = await request.get('/products');
  let products = [
  {
    id: 1,
    name: 'book'
  },
  {
    id: 2,
    name: 'book2'
  },
  {
    id: 3,
    name: 'book3',
  }
 ];
  expect(newRes.body).toEqual(products);
});

 

 

 

 

 

GitHub - hapijs/joi: The most powerful data validation library for JS

The most powerful data validation library for JS. Contribute to hapijs/joi development by creating an account on GitHub.

github.com

 

 

728x90
반응형