LoginSignup
1
2

More than 1 year has passed since last update.

Node.jsの基本

Last updated at Posted at 2021-10-14

はじめに

Node.jsの基本を備忘録として残しておきます。

目次

  1. Webアプリケーションの基本の3ステップ
  2. EJSテンプレートの使い方
  3. ルーティングの基本

Webアプリケーションの基本の3ステップ

  • requireでhttpオブジェクトを用意する。
const http = require('http');
  • createServerでサーバーを作る。
let server = http.createServer(ルーティング処理などを書いた関数);
  • listenで待ち受け開始する。
server.listen(3000);

EJSテンプレートの使い方

Webページの画面は基本的にEJSなどのテンプレートエンジンを利用します。
fsのreadFileSyncで読み込み、ejs.renderでレンダリングし、その結果をwriteで書き出す。

const fs = require('fs');
const ejs = require('ejs');
const index_page = fs.readFileSync('./index.ejs', 'utf8');
var content = ejs.render(index_page, {
                 title: "Index",
                 content: "これはIndexページです。",
              });
response.writeHead(200, { 'Content-Type': 'text/html' });
response.write(content);
response.end();
break;

ルーティングの基本

request.urlの値を取り出し、url.parseでパースして得られたオブジェクトから「pathname」を取り出し、その値に応じて処理を作成す。

const url = require('url');
let url_parts = url.parse(request.url);

switch (url_parts.pathname) {

    case '/':
      var content = ejs.render(index_page, {
        title: "Index",
        content: "これはIndexページです。",
      });
      response.writeHead(200, { 'Content-Type': 'text/html' });
      response.write(content);
      response.end();
      break;

    case '/other': 

・・・・・・

全文コード

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

const index_page = fs.readFileSync('./index.ejs', 'utf8');
const other_page = fs.readFileSync('./other.ejs', 'utf8');
const style_css = fs.readFileSync('./style.css', 'utf8');

var server = http.createServer(getFromClient);

server.listen(3000);
console.log('Server start!');

// ここまでメインプログラム==========

// createServerの処理
function getFromClient(request, response) {

  var url_parts = url.parse(request.url);
  switch (url_parts.pathname) {

    case '/':
      var content = ejs.render(index_page, {
        title: "Index",
        content: "これはIndexページです。",
      });
      response.writeHead(200, { 'Content-Type': 'text/html' });
      response.write(content);
      response.end();
      break;

    case '/other': //★追加
      var content = ejs.render(other_page, {
        title: "Other",
        content: "これは新しく用意したページです。",
      });
      response.writeHead(200, { 'Content-Type': 'text/html' });
      response.write(content);
      response.end();
      break;

    default:
      response.writeHead(200, { 'Content-Type': 'text/plain' });
      response.end('no page...');
      break;
  }
}
1
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2