Node.js ejs, jade module basic

ejs module

We can install ejs module by this code.

1
npm install ejs;

Then, npm installs eternal modules.
We can use those by the same way to internal modules.

1
var ejs = require('ejs');

Module ejs is the engine of template.
So it translates specific String to HTML type String.

We will make the server page which changes ejs page to HTML page.
When we translate ejs to HTML page, we use render(str, data, option) of ejs module.

Though we can use variables after declaring in ejs in side,
usually people declare them in Javascript and pass them to ejs for using.
When we pass Javascript‘ variables, we use the 2nd parameter of render() method like 9, 10th row.

Tip — we should set UTF-8 as that file’s encoding

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var http = require("http");
var fs = require('fs');
var ejs = require('ejs');

http.createServer(function ( request, response){
fs.readFile("ejsPage.ejs", 'utf8', function(error, data){
response.writeHead(200, {'Content-Type':'text/html'});
response.end(ejs.render(data, {
name: 'booski',
description : 'Hellow ejs with node.js'
}));
});
}).listen(52273, function(){
console.log("Server Running at http://127.0.0.1.52273");
});

When we write ejs page, we can use some special tags.

  • <% Code %> → writing Javascript code inside
  • <%= Value %> → printing the data

With using these tags, I made ejsPage.ejs file like this.

1
2
3
4
5
6
<h1><%=name%></h1>
<p><%=description%></p>
<hr/>
<%for(var i = 0;i<10;i++){%>
<h2>The Square of <%= i %> is <%= i*i%></h2>
<%}%>

Starting the server, we can see this page.


Jade module

Jade module is one of template engine modules too like ejs module.
We can install that by the same way to ejs like this

1
npm install jade

When jade module translates jade page to HTML page, it uses compile(string,option)method.
One different thing is that if ejsrender() returns String, compile() returns a function. And we can pass Javascript‘ variable with the function.
We put them as the parameter of the function which compile() returned like 11, 12 rows.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var http = require("http");
var fs = require('fs');
var jade = require('jade');

http.createServer(function ( request, response){
fs.readFile("jadePage.jade", 'utf8', function(error, data){
var fn = jade.compile(data);

response.writeHead(200, {'Content-Type':'text/html'});
response.end(fn({
name: 'booski',
description : 'Hellow jade with node.js'
}));
});
}).listen(52273, function(){
console.log("Server Running at http://127.0.0.1.52273");
});

Jade has special way to write down the page too like ejs.
The most important thing is making an indentation.
Jade module makes new HTML tag based on each indentations.

Tip: we should use ‘tap’ or ‘space bar’ for every indentation. If not, there will be an error

When we input words in the tag, we go to the next row and make an indentation again and then write down them there.
And If we want to give an attribute to the tag, we give it with parenthesis.
(if we want to give many attributes, we divide them by ,)

Jade translates some specific words in special way like doctype or annotation,

  • doctype html<!DOCTYPE html>
  • // JADE String<!-- JADE String -->

Especially making new div tag, we don’t need to write ‘div’ down.
If we write #header for example, that makes the div tag having ‘header’ as its id.
As the same way, .article makes the div having ‘article’ as its class.

Jade has special tags too.

  • -Code → writing Javascript code
  • #{Value} → printing the value (inputting the value between content)
  • =Value → printing the value (whole content becomes value)

Using these tags, we can make for repetitive statement like 11th row.

Based on what I mentioned, we can make this code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
doctype html
html
head
title index Page
body
// JADE String
#header
h1 hello jade...!
h2 #{name}, we are the World
h3= description
hr
- for(var i = 0; i< 10;i++) {
.article
p
a(href="https://medium.com/@booski/", data-test="attribute added") Go to new world #{i}
- }

And this code shows this page well.

Comments

MySql selecting duplicated data (by group by and in) 중복된 데이터 다 읽기

오늘 mysql 데이터베이스에 있는 데이터중 중복된 데이터를 확인해봐야할 일이 생겼다.
중복된 값이 있는 데이터들의 목록을 보는 것은 아래처럼 가능하다.

1
select * from (table name) group by (column name) having count(column name)>1;

하지만 이 경우, 각 중복값들에 대한 구체적인 내용은 볼 수가 없다.

오늘 해결해야했던 상황은 B컬럼에 중복된 값이 있는 경우 그 행들의 A컬럼 값을 비교하고 같은 데이터인지 등을 확인할 필요가 있었다.

따라서 B컬럼에서 각각의 값들이 중복된 값이 있는가를 확인해야 했고, 간단한 검색 후 다음 쿼리를 만들었다.
동작 원리는 B컬럼에서 중복된 값을 갖고 있는 값들의 리스트를 뽑고, 그 값들을 갖는 데이터를 모두 가져오는 방식이었다. (실제 사용때는 order by B, A를 사용해서 중복된 값들로 1차 정렬, 비교할 값들로 1차정렬하였다.)

1
select * from tableName where B in (select B from tableName group by B having count(B)>1);

다행이 잘 작동하였고, 이외에도 같은 구문내에서 where절과 order by절도 사용가능하였다.

Comments

MySql selecting duplicated data (by group by and in)

Today I needed to check some duplicated data from our database which uses mysql.
We can ‘see’ the list of duplicated data by using group by phrase like this.

1
select * from (table name) group by (column name) having count(column name)>1;

But in this case, we can’t check the details of those data.
The situation I needed to solve was that I needed to check A column’s values of the rows having same B column with any other data.

So, I needed to check all of the rows having any duplicated value in B column.
After searching a bit, I made this query. The way to work is like this.

  1. searching for the list of the data having same B value in any row
  2. selecting all data of the rows having same value of the result from 1.
  • I used order by B, A for sorting them by same B 1st and then A 2nd
1
select * from tableName where B in (select B from tableName group by B having count(B)>1);

This one worked how I expected and I could add where phrase and order by phrase too.

Comments

Node.js File System Module

Because we can’t write down all HTML page in Javascript file, we use file system module for provide HTML page which exists in server to clients.

For providing HTML page(HTMLPage.html), we need to make server javascript file like this.

1
2
3
4
5
6
7
8
9
10
11
const fs = require("fs");
const http = require("http");

http.createServer(function(request, response){
fs.readFile("HTMLPage.html", function(error, data){
response.writeHead(200, {"Content-Type:":"text/html"});
response.end(data);
});
}).listen(52273, function(){
console.log("server running at http://127.0.0.1:52273/");
});

If we want to provide another kind of file, we can change MIME type in 5th line.
For example, in jpeg case, we change text/html to image/jpeg.
It is same to other MIME types.

Examples of MIME

  • text/plain — basic text
  • text/html — HTML document
  • text/css — CSS document
  • text/xml — XML document
  • image/jpeg — JPG/JPEG image file
  • image/png — PNG image file
  • video/mpeg — MPEG video file
  • audio/mp3 — MP3 music file
Comments

Node.js http module

When we order chicken, we say ‘it is A apartment in B area, … please deliver us a chicken’ then we get a chicken after some time in the right place where we talked.

In this situation, putting URL on web browser is ordering chicken and getting the web page from the web server is getting the chicken from the restaurant. It’s the basic understanding about request and response

Depending on the way to send the ordering, we can call the server as HTTP web server or HTTPS web server etc.
When we use request message, we get proper web page for users.
When we use response message, we can save and take cookies and force to move the page.
In http module, the most important object is server. we can declare server by using createServer() method.

Server object’s method

1
2
listen(port[, callback]) — Start server
close([callback]) — Stop server

Server object’s event

1
2
3
4
5
6
request — when client asks something
connection — when client opens the server
close — when the server is closed
checkContinue — when client keeps connecting the server
upgrade — when client asks HTTP upgrade
clientError — when client makes errors

When we want to provide an web page, we need to write response message. And at that time, we use response object which is the 2nd parameter from request event listener.

Response object’s method

1
2
writeHead(statusCode[, statusMessage][, headers]) — write down the response header
end([data][, encoding][, callback]) — write the main response content

Comments