node.js = js의 실행환경 (브라우저가 아닌 곳에서도 실행시킬 수 있음)
웹 서버는
client한테 웹을 요청 받으면
이렇게 웹을 내놓는 애다.=
웹서버
= url이라는 주소로 요청을 받아서 요청받은 주소에 알맞는 웹사이트인데 html,css,js로 이루어진 웹 파일들을 브라우저에게 던저준다.
url = 웹서버의 주소
설치 완료 ㅎㅎ
확장자도 설치 했구요
console.log("hello vscode");
function a()
{
}
console.log("calc");
ㄴ이렇게 코드도 적어봤으요
//계산 기능을 하는 파일
const add = (a,b)=>a+b;
const sub = (a,b)=>a-b;
module.exports = { //객체 형식으로
moduleName : "calc module",
add:add,
sub:sub,
};
const calc = require("./calc"); //calc에 있는 module.export를 reqire을 써서 경로를 불러옴
console.log(calc); //출력
ㄴ이렇게 하면 터미널에서는
이렇게 객체 형식으로 출력된다
const calc = require("./calc"); //calc에 있는 module.export를 reqire을 써서 경로를 불러옴
console.log(calc.add(1,2));
console.log(calc.add(4,5));
console.log(calc.add(10,2));
ㄴ 계산기 여러개 함수 불러와도
잘 나온다
npm
= node package manager
-> node.js의 패키지 관리 도구
npm 어쩌고 해서 json파일 만들기
{
"name": "package-example1",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js" //요 문자열이 터미널에 입력이 돼서 명령이 실행된다
},
"author": "seoyeon",
"license": "ISC"
}
npm start
(json)
{
"name": "package-example1",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js"
},
"author": "seoyeon",
"license": "ISC"
}
(js)
console.log("hello nodejs package");
이걸 하고 터미널에 npm start를 하면
콘솔이 수행이 돼서 터미널에서 hello nodejs package 가 출력되는 것을 볼 수 있다
npm에서 다른 사람이 만든 모듈을 불러오기
npm js라고 치고 사이트 들어가서 randomcolor 검색
옆에 install 에서 코드 복사하자
터미널에 npm install randomcolor을 치자
바꼈다 !!
index.js에다가
const randomColor = require('randomcolor');
//경로 표시 안해도 reqire가 node module에서 잘 가져온다
let color1=randomColor();
let color2=randomColor();
let color3=randomColor();
console.log(randomColor());
이렇게 썼는데
강의에서는 이렇게 터미널에 랜덤값이 출력이 되지만
난 왜 안되냐???!!