const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res) => {
const url = req.url;
const method = req.method;
if(url === '/'){
res.write('<html>');
res.write('<head><title>Enter Message</title><head>');
res.write('<body>
<form action="/message" method="POST">
<input type="text" name="message">
<button type="submit">Send</button>
</form>
</body>');
res.write('</html>');
return res.end();
}
if(url === '/message' && method === 'POST'){
const body = [];
req.on('data', (chunk) => {
console.log(chunk);
body.push(chunk);
});
return req.on('end', () => { // body.push(chunk); 처리
const parsedBody = Buffer.concat(body).toString();
const message = parsedBody.split('=')[1];
fs.writeFile('message.txt',message, (err) => { // 동기처리
res.statusCode = 302;
res.setHeader('Location', '/');
return res.end();
});
});
}
res.setHeader('Content-Type', 'text/html')
res.write('<html>');
res.write('<head><title>My First Page</title><head>');
res.write('<body><h1>Hello from my Node.js Server!</h1></body>');
res.write('</html>');
res.end();
});
server.listen(4000);
...
if(url === '/'){
res.write('<html>');
res.write('<head><title>Enter Message</title><head>');
res.write('<body>
<form action="/message" method="POST">
<input type="text" name="message">
<button type="submit">Send</button>
</form>
</body>');
res.write('</html>');
return res.end();
}
if(url === '/message' && method === 'POST'){
const body = [];
req.on('data', (chunk) => {
console.log(chunk);
body.push(chunk);
});
return req.on('end', () => {
const parsedBody = Buffer.concat(body).toString();
const message = parsedBody.split('=')[1];
fs.writeFile('message.txt',message, (err) => {
res.statusCode = 302;
res.setHeader('Location', '/');
return res.end();
});
});
}
...
Node.js는 기본적으로 비동기 이벤트 처리를 하는것 같다. 그래서 위 함수를 이벤트에 등록 한 뒤에 바로 다음줄
...
res.setHeader('Content-Type', 'text/html')
res.write('<html>');
res.write('<head><title>My First Page</title><head>');
res.write('<body><h1>Hello from my Node.js Server!</h1></body>');
res.write('</html>');
res.end();
...
로 넘어간다.
이런식으로 상단의 코드를 먼저 실행하지 않는다는 것을 의미한다는 의미로 받아들였다. 즉, 코드나 함수를 등록해 지금 당장이 아니더라도 나중에 실행 될 수 있도록 하는 것이다. 따라서 다음 코드는 이전의 코드보다 먼저 실행 될 수 있다. 왜냐하면 이전 코드가 나중에 호출될 콜백이기 때문이다.