Node.jsでHello worldを表示してみる

VirtualBoxにCentOS7をインストールしてみる
の続き

Node.jsでHello worldを表示してみる。

インストール

epelからインストールする。

$ sudo yum -y install nodejs npm --enablerepo=epel

インストールされた。

$ node -v
v0.10.33

コマンドラインでHello, world!

example.jsを作成

$ vi example.js
console.log('Hello World\n');

実行すると、Hello worldが出力される

$ node example.js
Hello World

ブラウザからHello, world!

example.jsを作成

$ vi example.js
var http = require('http');

http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello World\n');
}).listen(8124);

console.log('Server running at http://127.0.0.1:8124/');

実行して、

$ node example.js
Server running at http://127.0.0.1:8124/

ブラウザからアクセスすると、Hello worldが表示される。

ファイルからHello, world!

example.jsを作成して、

$ vi example.js
var http = require('http');
var fs = require('fs');

http.createServer(function (request, response) {
  fs.readFile('example.html', function(err, content) {
    response.writeHead(200, {'Content-Type':'text/html; charset=utf-8'});
    response.end(content);
  });
}).listen(8124);

console.log('Server running at http://127.0.0.1:8124/');

HTMLファイルを作成する、

$ vi example.html
Hello World

実行して、ブラウザからアクセスすると、Hello worldが表示される。