npm이란

Node Package Manger

  • 노드의 패키지 매니저
  • 다른 사람들이 만든 소스 코드들을 모아둔 저장소
  • 남의 코드를 사용하여 프로그래밍 기능
  • 이미 있는 기능을 다시 구현할 필요가 없어 효율적
  • 오픈 소스 생태계를 구성중
  • 패키지 : npm에 업로드된 노드 모듈
  • 모듈이 다른 모듈을 사용할 수 있듯 패키지도 다른 패키지를 사용할 수 있음
  • 의존 관계라고 부름

package.json

현재 프로젝트에 대한 정보와 사용 중인 패키지에 대한 정보를 담은 파일

  • 같은 패키지라도 버전별로 기능이 다를 수 있으므로 버전을 기록해두어야 함
  • 동일한 버전을 설치하지 않으면 문제가 생길 수 있음
  • 노드 프로젝트 시작 전 package.json 부터 만들고 시작함(npm init)
D:\code\node\publish>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help init` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (publish) npmtest
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author: hd
license: (ISC) MIT
About to write to D:\code\node\publish\package.json:

{
  "name": "npmtest",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "hd",
  "license": "MIT",
  "description": ""
}


Is this OK? (yes) yes
// npm init 완료 하면 package.json 파일이 생성됨

// package.json
{
  "name": "npmtest",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "hd",
  "license": "MIT",
  "description": ""
}

 

>> npm run [스크립트명]으로 스크립트 생성

 

D:\code\node\publish>npm run test

> npmtest@1.0.0 test
> echo "Error: no test specified" && exit 1   //에러를 발생시키면서 프로세스를 종료

"Error: no test specified"

 

// 아래와 같이 설치를 하면 package.json 에 dependencies 에 버전이 표시된다.
// node_modules 디렉토리가 생성되면서 스크립트들이 생긴다.
D:\code\node\publish>npm i express

added 64 packages, and audited 65 packages in 8s

12 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

//package.json
{
  "name": "npmtest",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "hd",
  "license": "MIT",
  "description": "",
  "dependencies": {
    "express": "^4.19.2"
  }
}

 

// 아래와 같이 -D 옵션으로 설치를 하면 package.json 에 devDependencies에 버전이 표시된다.
// devDependencies는 개발할 때만 쓰이는 패키지들이다.
D:\code\node\publish>npm i -D nodemon

added 29 packages, and audited 94 packages in 6s

16 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

//package.json
  "devDependencies": {
    "nodemon": "^3.1.4"
  }

node_modules 크기가 크기 때문에 지워서 배포를 한다.(package.json 만 가지고 있다가 설치를 한다.)

npm i -g rimraf (-g는 글로벌 설치, 글로벌 설치는 dependencies 에 기록되지 않는다.)

npm i rimraf -D

npx 를 사용하면 글로벌 설치한 것처럼 사용이 가능하다.

글로벌 설치는 최대한 기피하는 것이 좋다.

SemVer 버저닝

노드 패키지의 버전은 SermVer(유의적 버저닝)방식을 따름

  • Major(주 버전), Minor(부 버전), Patch(수 버전)
  • 노드에서는 배포를 할 때 항상 버전을 올려야 함
  • Major는 하위 버전과 호환되지 않은 수정 사항이 생겼을 때 올림
  • Minor는 하위 버전과 호환되는 수정 사항이 생겼을 때 올림
  • Patch는 기능에 버그를 해결했을 때 올림

예) 1.0.7 ←- 1 : Major

        ←- 0 : Minor

              ←- 7 : Patch

버전 앞에 기호를 붙여 의미를 더함

dependencies에서 아래와 같이 고정된다는 뜻이다.

^1.0.7 : Major까지 고정

~1.0.7 : Minor까지 고정

1.0.7 : Patch까지 고정

  • @latest는 최신을 의미
  • @next로 가장 최신 배포판 사용 가능(불안정함)
  • 알파/베타/RC 버전이 존재할 수 있음

npm i express@latest ← 최신 버전 설치

npm i express@3 ← Major 3인 버전 설치

npm i express@3.5.1 ← 3.5.1 정확한 버전 설치

npm i express@next ← 가장 최신 배포판

 

npm outdated : 어떤 패키지에 기능 변화가 생겼는지 알 수 있음

npm uninstall 패키지명 : 패키지 삭제 (npm rm 패키지명 으로도 가능)

npm search 패키지명 : npm 패키지를 검색할 수 있음

npm info 패키지명 : 패키지의 세부 정보 파악 가능

D:\code\node\publish>npm search express

express
Fast, unopinionated, minimalist web framework
Version 4.19.2 published 2024-03-25 by wesleytodd
Maintainers: dougwilson linusu sheplu blakeembrey ulisesgascon wesleytodd mikeal
Keywords: express framework sinatra web http rest restful router app api
https://npm.im/express

D:\code\node\publish>npm info express

express@4.19.2 | MIT | deps: 31 | versions: 276
Fast, unopinionated, minimalist web framework
http://expressjs.com/


npm publish : 자신이 만든 패키지를 배포

npm unpublish : 자신이 만든 패키지를 배포 중단(배포 후 24시간 내에만 가능)

https://docs.npmjs.com/cli/v9/commands ←명령어 바뀌는 경우 있으니 사이트 참조

 

'Javascript > Node' 카테고리의 다른 글

노드 교과서 섹션 2  (0) 2023.09.05
노드 교과서 섹션 3  (0) 2023.09.01
노드 교과서 섹션 5  (0) 2023.08.29
노드 교과서 섹션 6  (0) 2023.08.27
노드 교과서 섹션 8  (0) 2023.08.23

express 와 nodemon 를 npm i 로 설치하고 아래와 같이 실행하면 익스프레스 서버가 실행된다.

 

// app.js

const express = require('express');

const app = express();

app.set('port', process.env.PORT || 3000);
app.get('/', (req, res)=>{
    res.send('hello express!');
});

app.listen(app.get('port'), ()=> {
    console.log('익스프레스 서버 실행');
});

 


// nodemon 으로 실행하면  파일에 변화가 있을 때마다 재기동을 해준다.
D:\code\node\6.1>nodemon app
[nodemon] 3.1.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,cjs,json
[nodemon] starting `node app.js`
익스프레스 서버 실행
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
익스프레스 서버 실행

// package.json 에서 scripts에 아래와 같이 되어 있으면 npm start 로도 실행이 가능하다.
  "scripts": {
    "start": "nodemon app"
  },

//실행 결과
D:\code\node\6.1>npm start

> express_test@1.0.0 start
> nodemon app

[nodemon] 3.1.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,cjs,json
[nodemon] starting `node app.js`
익스프레스 서버 실행

 

express 에서 html 파일 불러오기

 

//app.js
const express = require('express');
const path = require('path');
const app = express();

app.set('port', process.env.PORT || 3000);
app.get('/', (req, res)=>{
    res.sendFile(path.join(__dirname,'index.html'));
});

app.listen(app.get('port'), ()=> {
    console.log('익스프레스 서버 실행');
});

 

nodemon은 html 파일을 감시하지 않는다.

 

와일드카드는 보통 다른 라우터들보다 아래에 위치해야 정상적으로 작동된다.

미들웨어는 next()를 해주어야 그 다음 미들웨어가 실행된다.

미들웨어는 여러 개를 같이 사용도 가능하다.

에러 미들웨어는 반드시 next까지 4개가 다 들어있어야 한다.

서버가 클라이언트에게 status code를 마음대로 보낼 수가 있다.(에러가 발생해도)

 

res.json 은 응답을 보낼 뿐이지 return을 하는 것이 아니다.

 

// morgan cookie-parser express-session 설치
D:\code\node\6.1>npm i morgan cookie-parser express-session

added 11 packages, and audited 105 packages in 1s

16 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

 

morgan을 설치하고 실행한 후에 접속하면 비슷한 것 같지만 한 줄이 추가된다.

클라이언트에서 어떤 요청이 왔는지 서버에 기록된다.

얼마나 속도가 걸렸는지, 용량은 얼만큼인지(아래는 173 byte) , status code 도 같이 기록된다.

 

// 클라이언트에서 어떤 요청 왔는지 기록됨.
D:\code\node\6.1>npm start

> express_test@1.0.0 start
> nodemon app

[nodemon] 3.1.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,cjs,json
[nodemon] starting `node app.js`
익스프레스 서버 실행
모든 요청에 실행하고 싶어요.
GET / 200 10.919 ms - 173
모든 요청에 실행하고 싶어요.
GET /favicon.ico 404 1.772 ms - 14

 

// 개발시에는 dev
app.use(morgan('dev'));
//  실무에서는 combined 사용, 조금 더 자세해진다. ip , 시간, 요청 , 브라우저 등등 알 수 있다.
app.use(morgan('combined'));

 

app.use(cookieParser('zerochopassword'));
app.get('/', (req, res)=>{
    req.cookies // {mycookie : 'test}
    req.signedCookies; // 서명된 쿠키
    // 쿠키 생성 (name deprecated)
    res.cookie('name', encodeURIComponent(name), {
        expires: new Date(),
        httpOnly : true,
        path : '/',
    })
    // 쿠키 삭제 (name deprecated)
    res.clearCookie('name', encodeURIComponent(name),{
        httpOnly: true,
        path : '/',
    })
});

 

// bodyparser 가 express 안에 있다.
app.use(express.json()); // 클라이언트에서 json 데이터를 보냈을 때 파싱
app.use(express.urlencoded({extended: true})); //클라이언트에서 폼 데이터 보냈을 때 파싱
//extend가 true 면 qs, false 면 querystring (qs를 추천)

 

// 정적파일 처리
// app.use('요청경로',express.static('실제 경로'));
app.use('/',express.static(__dirname, 'public-3030')); // public은 유명하니깐 다른 것을 붙이는 것이 보안에 좋다.
//localhost:3000/zerocho.html         d:\code\node\6.1\public-3030\zerocho.html
//localhost:3000/hello.css         d:\code\node\6.1\public-3030\hello.css

 

'Javascript > Node' 카테고리의 다른 글

노드 교과서 섹션 3  (0) 2023.09.01
노드 교과서 섹션 4  (0) 2023.08.31
노드 교과서 섹션 6  (0) 2023.08.27
노드 교과서 섹션 8  (0) 2023.08.23
노드 교과서 섹션 9  (0) 2023.08.22

MySQL과 같은 SQL 데이터베이스와는 다른 유형의 데이터

  • NoSQL의 대표주자인 mongoDB(몽고디비)사용
SQL(MySQL) NoSQL(몽고디비)
규칙에 맞는 데이터 입력 테이블 간 JOIN 지원 안정성, 일관성 용어(테이블, 로우, 칼럼) 자유로운 데이터 입력 컬렉션 간 JOIN 미지원 확장성, 가용성 용어(컬렉션, 다큐먼트, 필드)

 

  • JOIN : 관계가 있는 테이블끼리 데이터를 합치는 기능(몽고디비 aggregate 흉내 가능)
  • 빅데이터, 메시징, 세션 관리 등(비정형 데이터)에는 몽고디비 사용하면 좋음
//몽고디비 실행 (아래 경로에서 shift 누르고 오른쪽 마우스 눌러서 powershell 실행
PS C:\Program Files\MongoDB\Server\7.0\bin> ./mongod --ipv6
{"t":{"$date":"2024-08-14T22:56:08.454+09:00"},"s":"I",  "c":"NETWORK",  "id":4915701, "ctx":"thread1","msg":"Initialized wire specification","attr":{"spec":{"incomingExternalClient":{"minWireVersion":0,"maxWireVersion":21},"incomingInternalClient":{"minWireVersion":0,"maxWireVersion":21},"outgoing":{"minWireVersion":6,"maxWireVersion":21},"isInternalClient":true}}}

 

//몽고쉘 실행
Please enter a MongoDB connection string (Default: mongodb://localhost/):

Current Mongosh Log ID: 66bcb84be9c5ca3e0a228fb4
Connecting to:          mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.2.15
Using MongoDB:          7.0.12
Using Mongosh:          2.2.15

For mongosh info see: https://docs.mongodb.com/mongodb-shell/


To help improve our products, anonymous usage data is collected and sent to MongoDB periodically (https://www.mongodb.com/legal/privacy-policy).
You can opt-out by running the disableTelemetry() command.

------
   The server generated these startup warnings when booting
   2024-08-14T22:56:09.973+09:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
   2024-08-14T22:56:09.973+09:00: This server is bound to localhost. Remote systems will be unable to connect to this server. Start the server with --bind_ip <address> to specify which IP addresses it should serve responses from, or with --bind_ip_all to bind to all interfaces. If this behavior is desired, start the server with --bind_ip 127.0.0.1 to disable this warning
------

test>
// admin 으로 변경
test> use admin
switched to db admin
// root 계정 생성
admin> db.createUser({user:'root', pwd:'manager', roles: ['root']})
{ ok: 1 }

 

mongod 있는 화면 끄고 다시 재실행

// --auth 붙여서 다시 실행
PS C:\Program Files\MongoDB\Server\7.0\bin> ./mongod --ipv6 --auth
{"t":{"$date":"2024-08-14T23:07:03.228+09:00"},"s":"I",  "c":"NETWORK",  "id":4915701, "ctx":"thread1","msg":"Initialized wire specification","attr":{"spec":{"incomingExternalClient":{"minWireVersion":0,"maxWireVersion":21},"incomingInternalClient":{"minWireVersion":0,"maxWireVersion":21},"outgoing":{"minWireVersion":6,"maxWireVersion":21},"isInternalClient":true}}}

 

//몽고쉘 경로에서 shift 누르고 오른쪽 마우스로 파워셀 열고 아래와 같이  root 계정으로 접속
PS C:\Users\john\Downloads\mongosh-2.2.15-win32-x64\mongosh-2.2.15-win32-x64\bin> ./mongosh admin -u root -p manager
Current Mongosh Log ID: 66bcbaa044900f7385228fb4
Connecting to:          mongodb://<credentials>@127.0.0.1:27017/admin?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.2.15
Using MongoDB:          7.0.12
Using Mongosh:          2.2.15

For mongosh info see: https://docs.mongodb.com/mongodb-shell/

------
   The server generated these startup warnings when booting
   2024-08-14T23:07:03.627+09:00: This server is bound to localhost. Remote systems will be unable to connect to this server. Start the server with --bind_ip <address> to specify which IP addresses it should serve responses from, or with --bind_ip_all to bind to all interfaces. If this behavior is desired, start the server with --bind_ip 127.0.0.1 to disable this warning
------

admin>

 

컬렉션 생성하기

따로 생성할 필요 없음

  • 다큐먼트를 넣는 순간 컬렉션도 자동 생성됨 ( mysql과 비교하며 컬렉션 : 테이블, 다큐먼트 : 데이터 로우)
  • 직접 생성하는 명령어도 있음
// 컬렉션 직접 생성하는 명령어 ( db를 nodejs로  잘 선택해서 생성하기)
admin> use nodejs;
switched to db nodejs
nodejs> show dbs;
admin   132.00 KiB
config  108.00 KiB
local    72.00 KiB
nodejs> db
nodejs
nodejs> db.createCollection('users')
{ ok: 1 }
nodejs> db.createCollection('comments')
{ ok: 1 }
nodejs> show collections
comments
users
nodejs>

 

insert 명령어

 

// insert 한개는 insertOne, insert 여러개는 insertMany
// 몽고디비는 오타 체크를 안하니 주의하기
nodejs> db.users.insertOne({ name : 'zero', age: 24, married: false, comment: '안녕하세요. 간단히 몽고디비 사용 방법에  대해 알아봅시다.', createdAt: new Date() });
{
  acknowledged: true,
  insertedId: ObjectId('66bcbdc744900f7385228fb5')
}
nodejs> db.users.insertOne({ name : 'nero', age : 32, married: true, comment: '안녕하세요. zero 친구 nero입니다.', createdAt: new Date() });
{
  acknowledged: true,
  insertedId: ObjectId('66bcbe7144900f7385228fb6')
}

// 조회하기
nodejs> db.users.find({name:'zero'})
[
  {
    _id: ObjectId('66bcbdc744900f7385228fb5'),
    name: 'zero',
    age: 24,
    married: false,
    comment: '안녕하세요. 간단히 몽고디비 사용 방법에 대해 알아봅시다.',
    createdAt: ISODate('2024-08-14T14:23:03.633Z')
  }
]


// users에 해당하는 ObjectId를 아래와 같이  복사해서 insert 하는 명령어
nodejs> db.comments.insertOne({ commenter: ObjectId('66bcbdc744900f7385228fb5'), comment: '안녕하세요. zero의 댓글입니다.', createdAt: new Date() });
{
  acknowledged: true,
  insertedId: ObjectId('66bcbf5d44900f7385228fb7')
}
nodejs>

 

조회 명령어

// 조회하기 (find는 전체 조회, findOne으로 하나만 조회)
nodejs> db.users.find({});
[
  {
    _id: ObjectId('66bcbdc744900f7385228fb5'),
    name: 'zero',
    age: 24,
    married: false,
    comment: '안녕하세요. 간단히 몽고디비 사용 방법에 대해 알아봅시다.',
    createdAt: ISODate('2024-08-14T14:23:03.633Z')
  },
  {
    _id: ObjectId('66bcbe7144900f7385228fb6'),
    name: 'nero',
    age: 32,
    married: true,
    comment: '안녕하세요. zero 친구 nero입니다.',
    createdAt: ISODate('2024-08-14T14:25:53.749Z')
  }
]
nodejs> db.comments.find({});
[
  {
    _id: ObjectId('66bcbf5d44900f7385228fb7'),
    commenter: ObjectId('66bcbdc744900f7385228fb5'),
    comment: '안녕하세요. zero의 댓글입니다.',
    createdAt: ISODate('2024-08-14T14:29:49.856Z')
  }
]

 

두 번째 인수로 조회할 필드를 선택할 수 있음(1은 추가, 0은 제외)

nodejs> db.users.find({}, {_id : 0, name :1 , married:1 });
[ { name: 'zero', married: false }, { name: 'nero', married: true } ]

 

첫 번째 인수로 조회 조건 입력 가능

  • $gt나 $or같은 조건 연산자 사용
nodejs> db.users.find({ age: {$gt: 30}, married: true }, {_id : 0, name: 1, age: 1 });
[ { name: 'nero', age: 32 } ]
nodejs> db.users.find({ $or: [{ age : {$gt: 30}}, {married : false }]}, {_id : 0, name:1, age: 1});
[ { name: 'zero', age: 24 }, { name: 'nero', age: 32 } ]

 

update 명령어

 

nodejs> db.users.updateOne({name :'nero'}, {$set: { comment : '안녕하세요. 이 필드를 바꿔보겠습니다.'}});
{
  acknowledged: true, //정상반영
  insertedId: null,
  matchedCount: 1,  //하나를 찾아서
  modifiedCount: 1,  // 하나를 변경햇다.
  upsertedCount: 0
}

 

delete 명령어

//delete 명령어
nodejs> db.users.deleteOne({name: 'nero'});
{ acknowledged: true, deletedCount: 1 }

// delete 된 것 확인
nodejs> db.users.find({});
[
  {
    _id: ObjectId('66bcbdc744900f7385228fb5'),
    name: 'zero',
    age: 24,
    married: false,
    comment: '안녕하세요. 간단히 몽고디비 사용 방법에 대해 알아봅시다.',
    createdAt: ISODate('2024-08-14T14:23:03.633Z')
  }
]

 

 

'Javascript > Node' 카테고리의 다른 글

노드 교과서 섹션 4  (0) 2023.08.31
노드 교과서 섹션 5  (0) 2023.08.29
노드 교과서 섹션 8  (0) 2023.08.23
노드 교과서 섹션 9  (0) 2023.08.22
노드 교과서 섹션 10  (0) 2023.08.19

+ Recent posts