NodeJS EJS

EJS

Embedded JavaScript
Install

npm install ejs

File : .ejs
Style

<%=val %>

Sample – index.ejs

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title><%=title %></title>
  <link type="text/css" href="style.css" rel="stylesheet">
</head>
<body>
  <h1><%=title %></h1>
  <p><%=msg %></p>
</body>
</html>

title, msg are parameters

Sample(JavaScript) – main.js

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

var index = fs.readFileSync('index.ejs', 'utf8');
var style = fs.readFileSync('style.css', 'utf8');

var server = http.createServer();
server.on('request', doRequest);
server.listen(1337);

function doRequest(req, res) {
	var path = url.parse(req.url);
	
	switch(path.pathname) {
	case '/':
		var tmp = ejs.render(index, {title: "Sample", msg: "This is sample"});
                // path data to ejb using hash 
		res.setHeader('Content-Type', 'text/html');
		res.write(tmp);
		res.end();
		break;
	case '/style.css':
		res.setHeader('Content-Type', 'text/css');
		res.write(style);
		res.end();
		break;
	default:
		res.setHeader('Content-Type', 'text/plain');
		res.write('ERROR');
		res.end();
		break;
	}
}
console.log('Server running at http://127.0.0.1:1337');

Set parameters in here.(Pass parameters to .ejs)

EJS Codes

JavaScript in <%%

<%
var dt = new Date();
var y = dt.getFullYear();
var m = dt.getMonth();
var d = dt.getDate();
%>

stylesheet

We need to handle stylesheet in javascript.

var fs = require('fs');
var style = fs.readFileSync('style.css', 'utf8');
res.setHeader('Content-Type', 'text/css');
res.write(style);
res.end();

Jade vs EJS

Design -> EJS
Program -> jade