goal
node.js ๐ฏ๏ธ
์น์๋ฒ
- http๋ผ๋ ๋ชจ๋์ ๊ฐ์ง๊ณ ์์ ์ด๋ฅผ ์ด์ฉํ์ฌ ์๋ฒ๋ฅผ ์์ฑ
const server = require('http');
server.createServer(function(req, res){
res.writeHead(200, { 'Content-Type' : 'text/plain' });
res.end("Hello node.js! \n");
}).listen(3000, 'localhost');
console.log('Server is running at http://localhost:3000/');
ํ์ผ ์ฝ๊ธฐ
- fs๋ผ๋ ํ์ผ ๋ชจ๋์ ๊ฐ์ง๊ณ ์์
readFile
์ด๋ผ๋ ๋น๋๊ธฐ ๋ฉ์๋๋ฅผ ํตํด ํ์ผ์ ์ฝ๊ณ ํด๋น ๋ด์ฉ์ ์ถ๋ ฅ
const fs = require("fs");
fs.readFile('./hello.txt', encoding = 'utf-8', function(err, data) {
if (err) {
throw err;
}
console.log(data + " Node.js!");
});
hello.txt
์๋
๋๋ ์ ์์ด์ผ!
๋น๋๊ธฐ ์ด๋ฒคํธ ์ด์ฉ
- events๋ผ๋ ๋ชจ๋์ ๋
ธ๋์์ ๋น๋๊ธฐ ์ด๋ฒคํธ๋ฅผ ์์ฑํ๊ณ ๊ด๋ฆฌํ๋๋ก ํด์ฃผ๋ ๋ชจ๋
var EventEmitter = require("events").EventEmitter;
var evt = new EventEmitter();
evt.on("helloNode", function(str) {
console.log("Hello! " + str );
});
setTimeout(function() {
evt.emit("helloNode", "Node.js");
}, 3000);
commonJS ๐ฏ๏ธ
node.js๋ common.js๊ท๊ฒฉ์ ๋ฐ๋ฆ
<script src="require.js"></script>
๋ก ๋ถ๋ฌ์จ ํ, module.exports
๋ก ๋ชจ๋ํ์ํค๊ณ ์ถ์ ๋ณ์๋ฅผ ๋ฌถ์ด์ค๋ค.
exports
๋ฅผ ํตํด ๊ฐ์ฒด๋ฅผ ๋ง๋ค ์ ์๋ค.
var exports = module.exports = {};
const http = require('http');
const delilah = require('delilah');
module.exports = {
a: http,
b: delilah,
};
const main = require('main');
console.log(main.a, main.b);
- ๋ชจ๋์ ํต์ฌ์ ๋ง๋ค์ด์ ๋ฐ๊นฅ์ผ๋ก ๋ด๋ณด๋ด๋ ๊ฒ
- ๋ชจ๋ ๋ชจ๋์ ์์ ๋ง์ ๋
๋ฆฝ์ ์ธ ์คํ ์์ญ์ ๊ฐ์ : exportsํ ๊ฒ๊ณผ ํ์ง ์์ ๊ฒ์ ๊ตฌ๋ถ
- ๋ชจ๋ ์ ์๋ ์ ์ญ๊ฐ์ฒด์ธ
exports
๊ฐ์ฒด๋ฅผ ์ด์ฉ
- ๋ชจ๋ ์ฌ์ฉ์
require
ํจ์๋ฅผ ์ด์ฉ
module.exports VS exports
exports
๋ module.exports
์ฌ์ฉ์ ๋์์ฃผ๋ helper
exports
๋ module.exports
๋ฅผ ์ฐธ์กฐํ๋ ์ญํ only
module.exports
์ ์ด๋ฏธ ๊ฐ์ด ํ ๋น๋๋ฉด, exports
๋ ๋ฌด์๋จ
- ๋ฐ๋ผ์, ๋์ ์์ด์ ์ฐ์ง ๋ง์์ผ ํจ
๋ฌธ์ ํ์ด๋ก ์์๋ณด๋ Common JS ๐ฏ๏ธ
[ ๋ฌธ์ 2 ]
let mod1 = require('./lib/my-module.js');
let mod2 = require('./lib/my-module.js');
mod1.increment();
let result = mod2.increment();
let counter = 0;
exports.increment = function () {
counter += 1;
return counter;
};
[ ๋ฌธ์ 3 ]
let mod1 = require('./lib/my-module.js');
let mod2 = require('./lib/my-module.js');
console.log("Loading module!")
[ ๋ฌธ์ 4 ]
console.log("A");
setTimeout(function() {
console.log("B");
}, 1000);
superLongComputation();
setTimeout(function() {
console.log("C");
}, 500);
console.log("D");
[ ๋ฌธ์ 5 ]
console.log("A");
setTimeout(function() {
console.log("B");
}, 500);
setTimeout(console.log("C"), 1000);
[ ๋ฌธ์ 6 ]
console.log("A");
setTimeout(go(), 100);
setTimeout(function() {
console.log("B");
}, 50);
function go () {
console.log("X")
}
[ ๋ฌธ์ 7 ]
console.log("A");
setTimeout(go, 100);
setTimeout(function() {
console.log("B");
}, 50);
function go () {
console.log("X")
}
AMD (Asynchronous Module Definition, ๋น๋๊ธฐ์ ๋ชจ๋ ์ ์ธ) ๐ฏ๏ธ
<script src="require.js"></script>
๋ก ๋ถ๋ฌ์จ ํ, ๋ณธ์ธ์ด ์ํ๋ ๋ค๋ฅธ ์ฝ๋๋ค์ define
์ ์ฒซ๋ฒ์งธ ์ธ์์ธ ๋ฐฐ์ด ์์ ๋์ดํ ํ, ๋๋ฒ์งธ ์ธ์์ธ ์ฝ๋ฐฑ ํจ์์์ ๋งค๊ฐ๋ณ์๋ก ๋ฐ๋๋ค.
define(['jquery', 'delilah'], function(apple, banana) {
return {
a: apple,
b: banana,
}
});