サーバーを起動する - Node.js

サーバーを起動してみる

「 app.js 」というファイルを作成し、コマンドプロンプトでアプリケーションを起動します。

アプリを起動するには、ファイルがあるディレクトリに移動し、「 node app.js 」とコマンドを入力します。

app.js

const http = require('http');

var server = http.createServer(
  (req, res) => {
    res.end('Hello, World');
  }
);

server.listen(3030);
console.log('Server Start');

HTMLファイルを開く

「 app.js 」ファイルと同じディレクトリに「 index.html 」というファイルを追加し、アプリケーションを起動します。

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <h1>Hello, World</h1>
</body>
</html>

app.js

const http = require('http');
const fs = require('fs');

var server = http.createServer(
  (req, res) => {
    fs.readFile('./index.html', 'UTF-8',
      (error, data) => {
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.write(data);
        res.end();
      }
    );
  }
);

server.listen(3030);
console.log('Server Start');

簡易サーバーを作る

CSS や Javascript も読み込む簡易サーバーを作成します。

Apache などの Web サーバーをインストールせずに CORS を回避する際などに利用できます。

  • example
    • index.html
    • script.js
    • server.js
    • style.js

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <script src="script.js"></script>
  <link rel="stylesheet" href="style.css">
  <title>sample</title>
</head>
<body>
  <h1>Hello, World</h1>
</body>
</html>

script.js

window.onload = function(){
  console.log("hello")
}

server.js

const http = require("http");
const fs = require('fs');
const url = require('url');
const port = "5000";

const index = fs.readFileSync('./index.html', 'utf8');
const styleCss = fs.readFileSync('./style.css', 'utf8');
const scriptJs = fs.readFileSync('./script.js', 'utf8');

let server = http.createServer(getClient);
server.listen(port);
console.log('Server Start');

function getClient(req, res) {
  const url_parts = url.parse(req.url);
  switch(url_parts.pathname){
    case "/":
      res.writeHead(200, { 'Content-Type': 'text/html' });
      res.write(index);
      res.end();
      break;
    case "/style.css":
      res.writeHead(200, { 'Content-Type': 'text/css' });
      res.write(styleCss);
      res.end();
      break;
    case "/script.js":
      res.writeHead(200, { 'Content-Type': 'text/javascript' });
      res.write(scriptJs);
      res.end();
      break;
    case "/module.js":
      res.writeHead(200, { 'Content-Type': 'text/javascript' });
      res.write(moduleJs);
      res.end();
      break;
  }
}

style.js

h1 {
  font-size: 14px;
}