hashiwa’s blog

技術的なメモを徒然と置いていきます。

Node.js事始め

インストール&セットアップ

  1. https://nodejs.org/ja/から推奨版(このときはV6.9.4)をダウンロードしてくる
  2. 任意のディレクトリに展開
  3. アプリを書く
  4. 実行

※本筋とは関係ないけど、xz形式ファイルの解凍が初めてでやり方わからなかったのですが、xzコマンドなんてあるんですね。

$ xz -dc node-v6.9.4-linux-x64.tar.xz | tar xfv -

アプリは、Node.js公式ページのExampleを参考にしました。

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World!\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

nodeコマンドで実行。

$ node-v6.9.4-linux-x64/bin/node example.js
Server running at http://127.0.0.1:3000/

ブラウザでhttp://127.0.0.1:3000/を開いて、Hello World! が表示されればOK。