NodeJS httpモジュールの使い方例【webサーバ/クライアントの作成】


本論文の実例はNodeJS httpモジュールの使い方を述べている。皆さんに参考にしてあげます。具体的には以下の通りです。
Node.jsはhttpモジュールを提供し、HTTPサーバとクライアントを構築する。
Webサーバを作成

/**
 * node-http    
 */
let http = require('http');
let url = require('url');
let fs = require('fs');
//      
let server = http.createServer((req, res) => {
  //     
  let pathname = url.parse(req.url).pathname; //   `/index.html`
  console.log('      ' + pathname + '   ');
  //       
  fs.readFile(pathname.substr(1), (err, data) => {
    if (err) {
      console.log('      :' + err);
      //   404  
      res.writeHead(404, {
        'Content-Type': 'text/html'
      });
    }
    else {
      //    :200
      res.writeHead(200, {
        'Content-Type': 'text/html'
      });
      //       
      res.write(data.toString());
    }
    //     
    res.end();
  });
});
server.listen(8081);
console.log('     :http://localhost:8081,   :http://localhost:8081/index.html');

index.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Node http</title>
</head>
<body>
  <h1>Hi~</h1>
</body>
</html>

server.jsを実行して、ブラウザを開けてアクセスします。
クライアントを作成
client.js

/**
 * node http      
 */
let http = require('http');
//     
let options = {
  host: 'localhost',
  port: '8081',
  path: '/index.html'
};
//          
let callback = (res) => {
  //       
  let body = '';
  res.on('data', (data) => {
    body += data;
  });
  res.on('end', () => {
    console.log('      ');
    console.log(body);
  });
}
//         
let req = http.request(options, callback);
req.end();

server.jsを実行して、client.jsを実行します。
ここで述べたように皆さんのnode.jsプログラムの設計に役に立ちます。