Quantcast
Channel: プログラム の個人的なメモ
Viewing all articles
Browse latest Browse all 860

【Node.js】Node.js ~ 基本編 / npm ~

$
0
0

■ npm

npm : Node Package Manager
 * パッケージ(Package)を管理する(Manager)ツール

  => テンプレートエンジン「ejs (Embedded JavaScript)」をインストールする

動画

https://dotinstall.com/lessons/basic_nodejs/26209
https://dotinstall.com/lessons/basic_nodejs/26210

■ 設定

# バージョン確認
npm --version

# ローカルインストール (現在のフォルダのみにインストールする)
npm install ejs

# 確認
ls -l node_modules/ejs

=> 全体で行いたい場合は、グローバルインストール「npm install -g ejs (g:global)」

■ 構文

テンプレート読み込み

var template = fileSystem.readFileSync(__dirname + '【テンプレートパス】', 'utf-8');

出力

# エスケープ処理を行わない
<%= 【変数】 %>

# エスケープ処理を行う
<%- 【変数】 %>

■ サンプル

hello.ejs

<html>
<body>
<h1><%= title %></h1>
<h2><%= title2 %></h2>
<h3><%- subtitle %></h3>
<h4><%= index %> views</h4>
</body>
</html>

hello.js

// HTTPモ/File Systemジュールを呼び出す
var http = require('http'),
    fileSystem = require('fs'),
    ejs = require('ejs');

// 外部ファイルから取得
var settings = require('./settings.js');
var server = http.createServer();

var template = fileSystem.readFileSync(__dirname + '/hello.ejs', 'utf-8');

var index = 0;
server.on('request', function(request, response) {
    index++;
    var data = ejs.render(template, {
       title: "Hello",
       title2: "<b>Hello2</b>",
       subtitle: "<b>World</b>",
       index: index
     });
    response.writeHead(200, {'Content-Type': 'text/html'});
    response.write(data);
    response.end();
});

server.listen(settings.port, settings.host);
console.log("Server listening...");

出力結果

Hello
<b>Hello2</b>
World
1 views

関連記事

Node.js ~ 基礎知識編 ~

https://blogs.yahoo.co.jp/dk521123/37579720.html

Node.js ~ 基本編 / あれこれ ~

https://blogs.yahoo.co.jp/dk521123/37588122.html

Viewing all articles
Browse latest Browse all 860

Trending Articles