node.jsを使ってみる
- node.jsを使ってみる。
いわゆるサーバーサイドjavascript。javascriptはなんとなく読めるけど書けない。
程度の知識レベル。
-
- インストール。(apt-getしまくってるので必要なライブラリとかは不明)
https://github.com/joyent/node/wiki/Installation https://github.com/joyent/node/wiki/Troubleshooting-Installation $ wget http://nodejs.org/dist/node-v0.4.8.tar.gz $ tar xvfz node-v0.4.8.tar.gz $ cd node-v0.4.8 $ mkdir ~/local $ ./configure --prefix=$HOME/local/node $ make $ make install $ export PATH=$HOME/local/node/bin:$PATH
-
- サンプル1(コンソール hello world!)
http://www.publickey1.jp/blog/11/nodejs.html $ cat hello-world.js setTimeout(function() { //setInterval(function() { console.log("world"); }, 2000) console.log("hello"); $ node hello-world.js hello world
-
- サンプル2(webサーバーでhello world!)
$ cat web-server.js var http = require('http'); var s = http.createServer(function(req, res) { res.writeHead(200, { 'content-type' : 'text/plain' }); res.end("hello world\n"); }); s.listen(8000); $ node web-server.js & [1] 5834 $ curl localhost:8000 -i HTTP/1.1 200 OK content-type: text/plain Connection: keep-alive Transfer-Encoding: chunked hello world $ kill 5834
-
- サンプル2のレスポンス。
$ ab -n 100 -c 100 127.0.0.1:8000/ Time taken for tests: 0.025 seconds
-
- サンプル3(echoサーバー)
$ cat echo-server.js var net = require('net'); var server = net.createServer(function (socket) { socket.write("Echo server\r\n"); socket.pipe(socket); }); server.listen(1337, "localhost"); $ telnet localhost 1337
-
- サンプル4
// http://www.atmarkit.co.jp/fcoding/articles/websocket/01/websocket01a.html var net = require('net'); //var sys = require('sys'); var server = net.createServer(function (stream) { var array = []; stream.setEncoding('utf8'); stream.on('connect', function () { console.log("connected"); stream.write('connected\r\n'); }); stream.on('data', function (data) { array.push(data.slice(0,-2)); stream.write('res: '+ array.join(',') + '\n'); }); stream.on('end', function () { console.log("disconnected"); stream.end(); }); }); server.listen(8127, 'localhost'); // telnet localhost 8127でアクセス。入力した結果がarrayに保存されて返って来る。