1. Hello World 샘플 프로그램
$ vi ~/Node/chapter01/helloworld.js
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'content-type': 'text/plain'});
res.write('Hello World!\n');
res.end();
}).listen(8124);
console.log('Server running on 8124');
$ node helloworld.js
2. 비동기 함수로 만들기 (process.nextTick 사용)
var asynchFunction = function(data, callback) {
process.nextTick(function() {
callback(data);
});
}
function log(data) {
console.log(data);
}
asynchFunction("123", log);
3. 비동기 함수로 만들기 (setTimeout 사용)
function log(data) {
console.log(data);
}
setTimeout(log, 0, "456");
4. Server Socket
var net = require('net');
var server = net.createServer(function(conn) {
console.log('connected');
conn.on('data', function(data) {
console.log(data + ' from ' + conn.remoteAddress + ' ' +
conn.remotePort);
conn.write('Repeating: ' + data);
});
conn.on('close', function() {
console.log('client closed connection');
});
}).listen(8124);
console.log('listening on port 8124');
5. Client Socket
var net = require('net');
var client = new net.Socket();
client.setEncoding('utf8');
client.connect('8124', 'localhost', function() {
console.log('connected to server');
client.write('Who needs a browser to communicate?');
});
process.stdin.resume();
process.stdin.on('data', function(data) {
client.write(data);
});
client.on('data', function(data) {
console.log(data);
});
client.on('close', function() {
console.log('connection is closed');
});
6. dns 찾기
var dns = require('dns');
var querystring = require('querystring');
dns.lookup('burningbird.net', function(err, ip) {
if (err) throw err;
console.log(ip);
});
dns.reverse('173.255.206.103', function(err, domains) {
domains.forEach(function(domain) {
console.log(domain);
});
});
var url = require('url');
var urlObj = url.parse('http://examples.burningbird.net:8124/?file=main');
console.log(urlObj);
var qs = urlObj.query;
console.log(qs);
var urlString = url.format(urlObj);
console.log(urlString);
var vals = querystring.parse('file=main&file=secondary&type=html');
console.log(vals);
var qryString = querystring.stringify(vals);
console.log(qryString);
7. 객체 상속
var util = require('util');
function first() {
var self = this;
this.name = 'first';
this.test = function() {
console.log(self.name);
};
}
first.prototype.output = function() {
console.log(this.name);
}
function second() {
second.super_.call(this);
this.name = 'second';
}
util.inherits(second, first);
var two = new second();
function third(func) {
this.name = 'third';
this.callMethod = func;
}
var three = new third(two.test);
two.output();
two.test();
three.callMethod(); // this 는 three 객체를 참조하지만, var self 변수는 two 객체의 값임
8. EventEmitter 를 활용한 사용자 정의 Event 만들기
var events = require('events');
var em = new events.EventEmitter();
var counter = 0;
setInterval(function() {
em.emit('timed', counter++);
}, 3000);
em.on('timed', function(data) {
console.log('timed ' + data);
});
9. 일반 객체에 사용자 정의 Event 만들기
util.inherits(someobj, EventEmitter);
someobj.prototype.somemethod = function() { this.emit('eventname'); };
someobjinstance.on('eventname', function() { });
var util = require('util');
var eventEmitter = require('events').EventEmitter;
var fs = require('fs');
function inputChecker(name, file) {
this.name = name;
this.writeStream = fs.createWriteStream('./' + file + '.txt',
{'flags': 'a',
'encoding': 'utf8',
'mode': 0666});
};
util.inherits(inputChecker, eventEmitter);
inputChecker.prototype.check = function check(input) {
var command = input.toString().trim().substr(0,3);
if (command == 'wr:') {
this.emit('write', input.substr(3,input.length));
} else if (command == 'en:') {
this.emit('end');
} else {
this.emit('echo', input);
}
};
var ic = new inputChecker('Shelley', 'output');
ic.on('write', function(data) {
this.writeStream.write(data, 'utf8');
});
ic.on('echo', function(data) {
console.log(this.name + ' wrote ' + data);
});
ic.on('end', function() {
process.exit();
});
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function(input) {
ic.check(input);
});