반응형

1. Node.js와 NPM 설치하기 

https://nodejs.org/ko/download/

 

다운로드 | Node.js

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

nodejs.org

버전 확인.

 

2. VSCode에서 React 프로젝트 생성

> npm install -g create-react-app

> create-react-app my-app

npm install -g에서 -g옵션은 시스템 디렉터리에 패키지를 설치하는 것을 의미합니다.
-g 옵션이 없다면 module은 현재 디렉터리 내부에 로컬로 설치됩니다.

3. 'my-app' 디렉터리로 이동 후 'npm start' 명령어로 리액트 프로젝트 시작

반응형
반응형

moment 사용하기

# 폴더 생성 및 열기
mkdir moment_practice
cd moment_practice

# package.json 초기화
npm init -y

# moment.js 설치
npm install moment

현재 날짜: moment()

//현재 날짜: moment()
// moment_practice.js

const moment = require("moment");

// 현재 날짜
console.log("========== today ==========");
console.log(moment());

특정 날짜 지정: moment('date')

// 특정 날짜 지정: moment('date')
// 특정 날짜 지정
console.log("========== specific date ==========");
console.log(moment("2021-01-27", "YYYY-MM-DD")); // Moment<2021-01-27T00:00:00+09:00>

형식 지정: format()

// 형식 지정: format()
// 현재 날짜 형식 지정
console.log("========== format ==========");
let date = moment("2021-01-27");
// 년-월-일
console.log(date.format("YYYY-MM-DD")); // 2021-01-27
// 시:분:초
console.log(date.format("HH:mm:ss")); // 00:00:00
// 요일
console.log(date.format("dddd")); // Wednesday
// 년-월-일 요일
console.log(date.format("YYYY-MM-DD dddd")); // 2021-01-27
// 년-월-일 시:분:초
console.log(date.format("YYYY-MM-DD HH:mm:ss")); // 2021-01-27 00:00:00
// 년-월-일 요일 시:분:초
console.log(date.format("YYYY-MM-DD dddd HH:mm:ss")); // 2021-01-27 Wednesday 00:00:00
// 날짜 더하거나 빼기: add(), subtract()
// 날짜 더하거나 빼기
console.log("========== add or subtract day, month, year ==========");
console.log(moment("2021-01-27").add(1, "days")); // 2021-01-28
console.log(moment("2021-01-27").add(2, "months")); // 2021-03-27
console.log(moment("2021-01-27").add(2, "years")); // 2023-01-27
console.log(moment("2021-01-27").subtract(1, "days")); // 2021-01-26
console.log(moment("2021-01-27").subtract(2, "months")); // 2020-11-27
console.log(moment("2021-01-27").subtract(2, "years")); // 2019-01-27

날짜 더하거나 뺄 때 생길 수 있는 문제점
한 moment 변수를 기준으로 날짜를 연속적으로 더하거나 빼게 되면 해당 변수도 add or subtract 함수를 실행하는 도중 값이 변하게 된다.

// 날짜 더하거나 뺄 때 생길 수 있는 문제점
// 한 moment 변수를 기준으로 날짜를 연속적으로 더하거나 빼게 되면 해당 변수도 add or subtract 함수를 실행하는 도중 값이 변하게 된다.

// 날짜 더하고 뺄 때 문제점
console.log("========== problems when adding or subtracting dates ==========");
let now = moment("2021-01-27");
console.log(now.add(3, "days")); // 2021-01-30
console.log(now.subtract(5, "days")); // 2021-01-25
console.log(now); // 2021-01-25

// 해결 방법: clone()
//add or subtract를 하기 전에 clone() 함수를 사용하면 된다.

// 해결 방법
console.log("========== solutions to the above problems ==========");
let fixedNow = moment("2021-01-27");
console.log(fixedNow.clone().add(3, "days")); // 2021-01-30
console.log(fixedNow.clone().subtract(5, "days")); // 2021-01-22
console.log(fixedNow); // 2021-01-27

https://millo-l.github.io/Nodejs-moment-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0/

 

[Node.js] moment 사용하기

nodejs에서 moment.js를 사용해보자.

millo-L.github.io

 

반응형
반응형

[Node.js]  Path : 파일 경로를 다루고 변경하는 유틸리티가 포함되어 있다

https://nodejs.sideeffect.kr/docs/v0.10.0/api/path.html

 

Path Node.js v0.10.0 Manual & Documentation

Path# Stability: 3 - Stable This module contains utilities for handling and transforming file paths. Almost all these methods perform only string transformations. The file system is not consulted to check whether paths are valid. Use require('path') to use

nodejs.sideeffect.kr

path.normalize(p)#

'..'와 '.' 부분을 처리해서 문자열 경로를 정규화한다.

슬래시가 여러 개 있는 경우 슬래시 하나로 교체하고 경로의 마지막에 슬래시가 있는 경우에는 유지한다. windows에서는 역슬래시를 사용한다.

path.normalize('/foo/bar//baz/asdf/quux/..')
// returns
'/foo/bar/baz/asdf'

path.join([path1], [path2], [...])#

모든 아규먼트를 합쳐서 최종 경로로 정규화한다. 문자열이 아닌 아규먼트는 무시한다.

path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')
// returns
'/foo/bar/baz/asdf'

path.join('foo', {}, 'bar')
// returns
'foo/bar'

path.resolve([from ...], to)#

to를 절대경로로 변환한다.

to가 절대경로가 아니면 절대경로를 찾을 때까지 from 아규먼트들을 우측에서 좌측의 순서로 앞에 이어붙힌다.모든 from 경로를 사용한 후에도 절대경로를 찾지 못하면 현재 워킹 디렉토리를 사용한다. 최종 경로는 정규화되고 경로가 루트 디렉토리로 처리되지 않는한 마지막 슬래시는 제거한다. 문자열이 아닌 아규먼트는 무시한다.

이는 쉘에서 cd 명령어를 순서대로 실행한 것과 같다.

path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')

//-- 이는 다음과 비슷하다.:

cd foo/bar
cd /tmp/file/
cd ..
cd a/../subfile
pwd

//--다른 경로라 존재할 필요가 없거나 파일일 수도 있다는 점만이 다르다.

path.resolve('/foo/bar', './baz')
// returns
'/foo/bar/baz'

path.resolve('/foo/bar', '/tmp/file/')
// returns
'/tmp/file'

path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')
// if currently in /home/myself/node, it returns
'/home/myself/node/wwwroot/static_files/gif/image.gif'

 

path.relative(from, to)#

from에서 to까지의 상대경로를 처리한다.

때로는 두 개의 절대경로를 가지고 있고 하나에서 다른 하나로의 상대경로를 얻어야 한다. 사실 이는 path.resolve의 반대 변환이다. 이 의미를 다음 예제에서 보자.

path.resolve(from, path.relative(from, to)) == path.resolve(to)

//-----------------------------------------------

path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb')
// returns
'..\\..\\impl\\bbb'

path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')
// returns
'../../impl/bbb'

path.dirname(p)#

경로의 디렉토리이름을 반환한다. Unix의 dirname 명령어와 비슷하다.

path.dirname('/foo/bar/baz/asdf/quux')
// returns
'/foo/bar/baz/asdf'

path.basename(p, [ext])#

경로의 마지막 부분을 반환한다. Unix의 basename 명령어와 비슷하다.

path.basename('/foo/bar/baz/asdf/quux.html')
// returns
'quux.html'

path.basename('/foo/bar/baz/asdf/quux.html', '.html')
// returns
'quux'

path.extname(p)#

경로의 마지막 부분의 문자열에서 마지막 '.'에서부터 경로의 확장자를 반환한다. 경로의 마지막 부분에 '.'가 없거나 첫 글자가 '.'이라면 빈 문자열을 반환한다. 

path.extname('index.html')
// returns
'.html'

path.extname('index.')
// returns
'.'

path.extname('index')
// returns
''

path.sep#

플랫폼의 파일 구분자. '\\'나 '/'이다.

'foo/bar/baz'.split(path.sep)
// returns
['foo', 'bar', 'baz']

 

path.delimiter#

플랫폼에 특화된 경로 구분자인 ;나 ':'이다.

 

console.log(process.env.PATH)
// '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'

process.env.PATH.split(path.delimiter)
// returns
['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin']

반응형
반응형

 

SyntaxError: await is only valid in async function

 

 

1. 에러메세지 : SyntaxError: await is only valid in async function

2. 원인 : async없이 await사용.

3. 해결 : await는 async 안에서만 사용할 수 있다. 

해결한 코드 

 

export const home = async (req, res) => {
  const videos = await Video.find({});
  res.render("home", { pageTitle: "Home", videos });
};

 

반응형
반응형

[Node.js] 파일 업로드 하기 (multer 모듈 사용 )

 

참조 : https://junspapa-itdev.tistory.com/27

 

[Node.js 12강] 파일 업로드 하기 (multer 모듈 사용, 한번에 파일 여러개 업로드하기, 삽질한 결과 공

이번엔 nodejs에서 파일을 업로드하는 방법을 알아보도록 하겠습니다. 한번에 여러 이미지를 업로드하는 케이스를 개발했는데 상당히 삽질을 했습니다. 1개만 업로드 할 때는 쉽게 처리하는건 굉

junspapa-itdev.tistory.com

<form name="questionForm" method="post" enctype="multipart/form-data" action="/test/save">
  <input type="hidden" name="TEST_SN" value="1">
  
  <ul id="questionFormList">
    <li>
      <input type="hidden" name="Q_SN" value="2">
      <input type="file" name="IMG_FILE">
    </li>
    <li>
      ...
    </li>
    ...
  </ul>
  <input type="submit" value="전송">
</form>
var multer = require('multer');  //multer 모듈 import
var upload = multer({dest: 'public/images/yesno/'}); //업로드 경로 설정
//미리 폴더를 만들어놔야 하며, 경로 맨 앞에 '/'는 붙이지 않습니다.
var multer = require('multer');	

//multer 의 diskStorage를 정의
var storage = multer.diskStorage({
  //경로 설정
  destination : function(req, file, cb){    

    cb(null, 'publics/images/');
  },

  //실제 저장되는 파일명 설정
  filename : function(req, file, cb){
	//파일명 설정을 돕기 위해 요청정보(req)와 파일(file)에 대한 정보를 전달함
    var testSn = req.body.TEST_SN;
    var qSn = req.body.Q_SN;

    //Multer는 어떠한 파일 확장자도 추가하지 않습니다. 
    //사용자 함수는 파일 확장자를 온전히 포함한 파일명을 반환해야 합니다.        
    var mimeType;

    switch (file.mimetype) {
      case "image/jpeg":
        mimeType = "jpg";
      break;
      case "image/png":
        mimeType = "png";
      break;
      case "image/gif":
        mimeType = "gif";
      break;
      case "image/bmp":
        mimeType = "bmp";
      break;
      default:
        mimeType = "jpg";
      break;
    }

    cb(null, testSn + "_" + qSn + "." + mimeType);
  }
});

var upload = multer({storage: storage});

파일명 + 현재일시 추가

const multer = require("multer");
const path = require("path");

let storage = multer.diskStorage({
    destination: function(req, file ,callback){
        callback(null, "upload/")
    },
    filename: function(req, file, callback){
        let extension = path.extname(file.originalname);
        let basename = path.basename(file.originalname, extension);
        callback(null, basename + "-" + Date.now() + extension);
    }
});

// 1. 미들웨어 등록
let upload = multer({
    storage: storage
});

https://victorydntmd.tistory.com/39

반응형
반응형

 

nvm 활용하여 node, npm 설치하는 방법을 알아 보겠습니다.

sudo curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.1/install.sh | bash

설치 후 nvm 명령어가 실행이 되지 않는 다면 환경설정을 해주어야 합니다.

nano ~/.bashrc

아래 내용을 복사 후 저장합니다.

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm

설정을 로딩 하기 위해 아래 명령어를 실행 합니다.

source ~/.bashrc

명령어를 쳤을때 아래와 같이 나온다면 성공적으로 설치가 완료 된 것 입니다.

nvm ls

N/A
node -> stable (-> N/A) (default)
iojs -> N/A (default)

이제 최신 안정화된 node 버전을 설치 하면 됩니다.

공식 홈페이지에서 안정화된 버전을 확인하거나 팀내 또는 원하시는 버전이 있다면 그 버전을 설치 하시고 진행 하시면 됩니다.

저는 최신 안정화된 버전을 설치 하겠습니다.

nvm install 12.14.1


node -v 
v12.14.1

npm - v
6.13.4

firework-ham.tistory.com/20

 

[node] nvm 설치하기, node, npm 설치하기.

nvm 활용하여 node, npm 설치하는 방법을 알아 보겠습니다. 1 설치 sudo curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.1/install.sh | bash 2 설정 설치 후 nvm 명령어가 실행이 되지 않는..

firework-ham.tistory.com

 

반응형
반응형
PostgreSQL로 시작하는 SQL 코딩입문 Part 1 - 기본 편
국내도서
저자 : 박상용
출판 : 엔코아 2019.11.27
상세보기
PostgreSQL로 시작하는 SQL 코딩입문 Part 2 - 활용 편
국내도서
저자 : 박상용
출판 : 엔코아 2019.11.15
상세보기
Node.js 교과서
국내도서
저자 : 조현영
출판 : 길벗 2020.07.25
상세보기
개발자도 궁금한 IT 인프라
국내도서
저자 : 정송화,김영선,전성민
출판 : 제이펍 2018.06.11
상세보기

반응형
반응형

Node.js 웹서버로 만들기   http://localhost:3000

 

var http = require('http');
var fs = require('fs');
var app = http.createServer(function(request,response){
    var url = request.url;
    if(request.url == '/'){
      url = '/index.html';
    }
    if(request.url == '/favicon.ico'){
      //return response.writeHead(404);
      response.writeHead(404);
      response.end();
      return;
    }
    response.writeHead(200);
    console.log(__dirname + url);
    response.end(fs.readFileSync(__dirname + url));

});
app.listen(3000);

 

https://youtu.be/VGZTn1diz_I

 

opentutorials.org/course/3332/21032

 

Node.js - 웹서버 만들기 - 생활코딩

수업소개 Node.js는 웹서버 기능을 가지고 있습니다. 이런 특성을 이용해서 컨텐츠를 프로그래밍적으로 생산할 수 있게 됩니다. 여기서는 Node.js를 웹서버로 구동하는 방법을 살펴보겠습니다.  강

opentutorials.org

소스 : github.com/web-n/web1_html_internet

 

web-n/web1_html_internet

Contribute to web-n/web1_html_internet development by creating an account on GitHub.

github.com

 

반응형

+ Recent posts