

▲ REPL
// 콘솔
$ node
> const str="Hello node";
undefined
> console.log(str);
Hello node
모듈: 특정한 기능을 하는 함수나 변수들의 집합

// os.js
const os = require('os');
console.log('운영체제 정보---------------------------------');
console.log('os.arch():', os.arch());
console.log('os.platform():', os.platform());
console.log('os.type():', os.type());
console.log('os.uptime():', os.uptime());
console.log('os.hostname():', os.hostname());
console.log('os.release():', os.release());
console.log('경로------------------------------------------');
console.log('os.homedir():', os.homedir());
console.log('os.tmpdir():', os.tmpdir());
console.log('cpu 정보--------------------------------------');
console.log('os.cpus():', os.cpus());
console.log('os.cpus().length:', os.cpus().length);
console.log('메모리 정보-----------------------------------');
console.log('os.freemem():', os.freemem());
console.log('os.totalmem():', os.totalmem());
// path.js
const path = require('path');
const string = __filename;
console.log('path.sep:', path.sep);
console.log('path.delimiter:', path.delimiter);
console.log('------------------------------');
console.log('path.dirname():', path.dirname(string));
console.log('path.extname():', path.extname(string));
console.log('path.basename():', path.basename(string));
console.log('path.basename - extname:', path.basename(string, path.extname(string)));
console.log('------------------------------');
console.log('path.parse()', path.parse(string));
console.log('path.format():', path.format({
dir: 'C:\users\zerocho',
name: 'path',
ext: '.js',
}));
console.log('path.normalize():', path.normalize('C://users\\zerocho\\path.js'));
console.log('------------------------------');
console.log('path.isAbsolute(C:\):', path.isAbsolute('C:\'));
console.log('path.isAbsolute(./home):', path.isAbsolute('./home'));
console.log('------------------------------');
console.log('path.relative():', path.relative('C:\users\zerocho\path.js', 'C:\'));
console.log('path.join():', path.join(__dirname, '..', '..', '/users', '.', '/zerocho'));
console.log('path.resolve():', path.resolve(__dirname, '..', 'users', '.', '/zerocho'));
// url.js
const url = require('url');
const { URL } = url;
const myURL = new URL('http://www.gilbut.co.kr/book/bookList.aspx?sercate1=001001000#anchor');
console.log('new URL():', myURL);
console.log('url.format():', url.format(myURL));
// dns.mjs
import dns from 'dns/promises';
const ip = await dns.lookup('gilbut.co.kr');
console.log('IP', ip);
const a = await dns.resolve('gilbut.co.kr', 'A');
console.log('A', a);
const mx = await dns.resolve('gilbut.co.kr', 'MX');
console.log('MX', mx);
const cname = await dns.resolve('www.gilbut.co.kr', 'CNAME');
console.log('CNAME', cname);
const any = await dns.resolve('gilbut.co.kr', 'ANY');
console.log('ANY', any);
// worker_threads.js
const {
Worker, isMainThread, parentPort,
} = require('worker_threads');
if (isMainThread) { // 부모일 때
const worker = new Worker(__filename);
worker.on('message', message => console.log('from worker', message));
worker.on('exit', () => console.log('worker exit'));
worker.postMessage('ping');
} else { // 워커일 때
parentPort.on('message', (value) => {
console.log('from parent', value);
parentPort.postMessage('pong');
parentPort.close();
});
}
// test.py
print('hello python')
// spawn.js
const spawn = require('child_process').spawn;
const process = spawn('python', ['test.py']);
process.stdout.on('data', function(data) {
console.log(data.toString());
}); // 실행 결과
process.stderr.on('data', function(data) {
console.error(data.toString());
}); // 실행 에러
// writeFile.js
const fs = require('fs');
// writeFile 메서드에 생성될 파일의 경로와 내용 입력
fs.writeFile('./writeme.txt', '여기에 내용 입력', (err) => {
if (err) {
throw err;
}
// 파일 읽기
fs.readFile('./writeme.txt', (err, data) => {
if (err) {
throw err;
}
console.log(data.toString());
});
});

req: 요청에 관한 정보를 담는 객체. req.body, req.cookies, req.app 등의 메서드를 가짐.
res: 응답에 관한 정보를 담는 객체. res.writeHead, res.write, res.end, res.app, res.cookie 등의 메서드를 가짐.
HTTP 상태 코드: 브라우저는 서버가 보내준 상태 코드를 통해 요청의 성공 여부를 판별함.
//createServer.js
const http = require('http');
http.createServer((req, res) => {
// 여기에 어떻게 응답할지 적기
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); // 요청 성공(200)과 응답에 대한 정보 전송
res.write('<h1>Hello Node!</h1>'); // 클라이언트에게 보내는 데이터
res.end('<p>Hello Server!</p>'); // 데이터를 보낸 후 응답 종료
});
.listen(8080, () => { // 서버와 연결하기
console.log('서버 대기 중');
});
REST=REpresentational State Transfer
대표적인 HTTP 요청 메서드:


▲ 클러스터링
const fs = require('fs');
fs.writeFile('./writeme.txt', '여기에 내용 입력', (err) => {
if (err) {
throw err;
}
fs.readFile('./writeme.txt', (err, data) => {
if (err) {
throw err;
}
console.log();
});
});
const http = require('http');
http.( 1 )((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.write('<h1>Hello Node!</h1>');
res.end('<p>Hello Server!</p>');
});
.( 2 )(8080, () => {
console.log('서버 대기 중');
});
<빈칸QUIZ 답>
<코드작성QUIZ 답>
1. console.log() 안에 data.toString()을 넣지 않아 사람이 읽을 수 없는 버퍼가 출력된다.
2. createServer, listen
출처 : 조현영, 『 Node.js 교과서 개정 3판』, 길벗(2022)
node.js : https://nodejs.org/ko/learn
Corner Node.js 2
Editor Coin
| [Node.js 2팀] 8장. 몽고디비 (0) | 2025.11.21 |
|---|---|
| [Node.js 2팀] 7장. MySQL (1) | 2025.11.14 |
| [Node.js 2팀] 5장. 패키지 매니저~ 6장. 익스프레스 웹 서버 만들기 (0) | 2025.11.07 |
| [Node.js 2팀] 1장. 노드 시작하기 ~ 2장. 알아둬야 할 JavaScript (0) | 2025.10.10 |
| [Node.js 2팀] 1장 자바스크립트( Introductions ~ Objects ) (0) | 2025.10.03 |