ติดตั้ง express generator

การติดตั้ง express generator

ติดตั้งครั้งเดียว ไม่ได้ขึ้นกับโปรเจ็กส์

npm install express-generator -g

ดู version

> express --version
4.16.1

ดู help

> express -h

  Usage: express [options] [dir]

  Options:

        --version        output the version number
    -e, --ejs            add ejs engine support
        --pug            add pug engine support
        --hbs            add handlebars engine support
    -H, --hogan          add hogan.js engine support
    -v, --view <engine>  add view <engine> support (dust|ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade)
        --no-view        use static html instead of view engine
    -c, --css <engine>   add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)
        --git            add .gitignore
    -f, --force          force on non-empty directory
    -h, --help           output usage information

-v, --view แสดง view engine ที่ใช้ได้ dust | ejs | hbs | hjs | jade | pug | twig | vash

ทดลองสร้างโปรเจ็กส์

สร้างโปรเจ็กส์ด้วย express generator โดยใช้ Pug

> express --view=pug myapp

   create : myapp\
   create : myapp\public\
   create : myapp\public\javascripts\
   create : myapp\public\images\
   create : myapp\public\stylesheets\
   create : myapp\public\stylesheets\style.css
   create : myapp\routes\
   create : myapp\routes\index.js
   create : myapp\routes\users.js
   create : myapp\views\
   create : myapp\views\error.pug
   create : myapp\views\index.pug
   create : myapp\views\layout.pug
   create : myapp\app.js
   create : myapp\package.json
   create : myapp\bin\
   create : myapp\bin\www

   change directory:
     > cd myapp

   install dependencies:
     > npm install

   run the app:
     > SET DEBUG=myapp:* & npm start

จะได้ไฟล์ package.json

{
  "name": "myapp",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "cookie-parser": "~1.4.4",
    "debug": "~2.6.9",
    "express": "~4.16.1",
    "http-errors": "~1.6.3",
    "morgan": "~1.9.1",
    "pug": "2.0.0-beta11"
  }
}

เสร็จแล้วติดตั้ง dependencies:

> cd myapp
> npm install

สั่งรันโปรเจ็กส์บน MacOS or Linux

$ DEBUG=myapp:* npm start

สั่งรันโปรเจ็กส์บน Windows

> set DEBUG=myapp:* & npm start

ลองเปิด browser เข้าที่ http://localhost:3000/
จะเห็นข้อความ

Express
Welcome to Express

สร้างเว็บเซอร์เวอร์ด้วย Express

สร้างโฟลเดอร์ให้แอพชื่อ myapp

mkdir myapp
cd myapp

ใช้คำสั่ง npm init เพื่อสร้างไฟล์ package.json

> npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help init` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (myapp)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to D:\Project\node\myapp\package.json:

{
  "name": "myapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}


Is this OK? (yes) y

จะได้ไฟล์ package.json

{
  "name": "myapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

ติดตั้ง express ให้กับโปรเจ็กส์นี้

npm install express --save

ไฟล์ package.json จะเพิ่ม dependencies

{
  "name": "myapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  }
}

สร้างไฟล์ server.js

var express = require('express')
var app = express()
 
app.get('/', function (req, res) {
    res.send('Hello World')
})
 
app.listen(3000)
console.log("Server running at port 3000");

หรือ

const express = require('express')
const app = express()
const port = 3000
 
app.get('/', (req, res) => res.send('Hello World!'))
 
app.listen(port, () => console.log(`App listening on port ${port}!`))

ทดลองรัน

> node server.js
Server running at port 3000

เปิด browser ไปที่ http://localhost:3000/
จะเห็นข้อความ Hello World

การใช้ Node.js เบื้องต้น

  1. การใช้ Node.js ทาง Terminal
  2. การใช้ Node.js จากไฟล์ที่พิมพ์คำสั่งไว้
  3. สร้างเว็บเซอร์เวอร์ แสดงข้อความ Hello World

1. การใช้ Node.js ทาง Terminal

เปิด command prompt แล้วเรียกใช้งาน node ด้วยคำสั่ง node

node

สั่งพิมพ์ออกหน้า console ด้วย console.log

> console.log("OK");
OK
undefined

สร้างฟังก์ชัน sayHi()

> function sayHi() {return "HI";}
undefined
> sayHi();
‘HI’
>

ทดลองบวกเลข

> 10 + 10
20

To exit, press Ctrl+C again or Ctrl+D or type .exit

2. การใช้ Node.js จากไฟล์ที่พิมพ์คำสั่งไว้

ทดสอบโดยการสร้างไฟล์ JavaScript ขึ้นมา เช่น test.js 

console.log("Hello Node.js");
 
function sayHi() {
    return "Hi!";
}
 
console.log(sayHi());

คำสั่งที่ใช้ให้ Node รันไฟล์ JavaScript คือ node [filename] เช่น

node test.js

จะได้ผลลัพธ์ดังนี้

Hello Node.js
Hi!

3. สร้างเว็บเซอร์เวอร์ แสดงข้อความ Hello World

สร้างไฟล์ชื่อ server.js

var http = require("http");
http.createServer(function (req, res) {
    res.writeHead(200, { "Content-Type": "text/plain" });
    res.end("Hello World\n");
}).listen(1337, "127.0.0.1");
 
console.log("Server running at http://127.0.0.1:1337/");

บรรทัดที่ 1 : require(‘http’) เป็นการ import module http ซึ่งเป็น module หลักของ Node.js
บรรทัดที่ 2 : createServer() เป็นการสร้าง Server ของ Node.js โดยรับ function ที่มี request และ response
บรรทัดที่ 3 : res.writeHead() เป็นการกำหนด Content Type
บรรทัดที่ 4 : res.end() เป็นการสิ้นสุด response และส่งคำว่า Hello World
บรรทัดที่ 5 : .listen(port, address) เป็นการกำหนด port และ address ของเว็บ Server (address เป็น optional)

ทำการสั่งรันบน command line ด้วยคำสั่ง

node server.js

จากนั้นเปิดเว็บบราวเซอร์ที่ http://localhost:1337/
จะเห็นข้อความ Hello World แสดงบนจอภาพ

การติดตั้ง Node.js บน Windows

หน้าเว็บหลัก Node.js https://nodejs.org/

เมื่อดาว์นโหลดจะได้ไฟล์ node-v14.18.0-x64.msi

เมื่อติดตั้งโปรแกรมจะอยู่ที่ C:\Program Files\nodejs\

การติดตั้งจะได้ node และ npm (Node Package Manager) ซึ่งเป็นตัวจัดการ package/module ต่างๆของ Node มาด้วย

ดูเวอร์ชันของ node

> node -v
v14.18.0

ดูเวอร์ชันของ npm

> npm -v
6.14.15

อัพเดท npm ให้เป็นเวอร์ชันล่าสุด

npm i npm@latest -g

เมื่อดูเวอร์ชันของ npm อีกทีจะได้เวอร์ชันล่าสุดละ

> npm -v
7.24.2

ตั้งแต่ npm 5.2.0 จะได้ npx (Node Package Execute) ติดตั้งมาด้วย

> npx -v
7.24.2

ดู config ของ npm

npm config ls

หรือต้องการดู config ทั้งหมด

npm config ls -l

ดูเสร็จแล้วถ้าจะกำหนดค่า config ให้ทำแบบนี้

> npm config set strict-ssl false
> npm config set ca=null

TypeScript

ติดตั้ง typescript

npm install -g typescript

ติดตั้ง typescript เวอร์ชันล่าสุด

npm install -g typescript@latest

ตรวจสอบเวอร์ชันของ typescript

> tsc -v
Version 4.4.3