標籤

BAT (38) shell (34) Virtual Machine (33) Xubuntu (29) acfs (25) PHP (24) CentOS (21) Virtul Box (20) 編輯器 (17) 資料庫 (15) lubuntu (13) windows (13) CPP (12) ubuntu (12) chrome (11) laravel (10) Docker (9) Python (9) 5A88 (7) VMware (6) 資料結構 (6) Javascript (5) Node (5) Proxmox VE (5) 公告系統 (5) 程式積木 (5) Android Studio (4) ANN (3) OB2D2016x64 (3) Xoops (3) clonezilla (3) samba (3) 公文 (3) 其他 (3) 硬體 (3) API (2) Android (2) AppInvent2 (2) Html (2) Hyper-V (2) Nas (2) botnet (2) mbot (2) swift (2) wordpress (2) 樣板 (2) 防火牆 (2) AD的應用 (1) Ansible (1) Arduino (1) CSS (1) GitLab (1) HA Proxy (1) LegoEV3 (1) PowerShell (1) Scratch (1) VM (1) XenServer (1) kotlin (1) linuxmint (1) lxc (1)

2020年5月26日 星期二

Node.js 入門_筆記與學習心得

最近學Node.js 入門!!覺得需要將學到的程式碼做個整理,來讓自己更熟悉狀況。
以下是程式碼的調整與註記:

1.簡單的網頁伺服器ch06server.js並載入外部文件ch06config.js

檔案名稱:ch06config.js
檔案內容:
const config = {
    HostName:'127.0.0.1',
    PortName:'9000'
};
exports.config = config;

檔案名稱:ch06server.js
檔案內容:
const http = require('http');
const config = require('./ch06config').config;
const server = http.createServer((req,res) => {
          res.statusCode = 200;
          res.setHeader('Content-Type','text/plain');
          switch(req.url) {
            case '/':
               res.end(`This is a / page`);
               break;
            case '/test':
               res.end(`This is a test page`);
               break;
            case '/ok':
               res.end(`This is a ok page`);
               break;
             default:
                res.end(`Server running at http://${config.HostName}:${config.PortName}`);   
          }
});

server.listen(config.PortName,config.HostName,()=>{
    console.log(`Server running at http://${config.HostName}:${config.PortName}/`);
});

2.可運行ch08index.html的網頁伺服器ch08server.js並載入外部文件ch06config.js

檔案名稱:ch06config.js
檔案內容:
const config = {
    HostName:'127.0.0.1',
    PortName:'9000'
};
exports.config = config;

檔案名稱:ch08index.html
檔案內容:
<html>
   <head>
       <title>Nodejs running indexhtml</title>
   </head>
   <body>
       <p>Nodejs running index.html</p>
   </body>
</html>

檔案名稱:ch08server.js
檔案內容:
const http = require('http');
const config = require('./ch06config').config;
const fs = require('fs');

const server = http.createServer((req,res) => {
     fs.readFile(__dirname + '/ch08index.html','utf-8',function (err,data){
         if (err) {
            res.setHeader('Content-Type','text/plain');
            res.statusCode = 404;
            res.end('Not Founded.');
         } else {
            res.setHeader('Content-Type','text/html');
            res.statusCode = 200;
            res.end(data);
         }
     });
});
server.listen(config.port,config.hostname,() => {
     console.log(`Server running at http://${config.hostname}:${config.port}/`);
});

接下來,我將1、2的程式碼整合一下。

3.將1、2的程式碼整合

檔案名稱:ch00index.html
檔案內容:
<html>
   <head>
       <title>Nodejs running ch00indexhtml</title>
   </head>
   <body>
       <h1>Nodejs running ch00index.html</h1>
   </body>
</html>

檔案名稱:ch00home01.html
檔案內容:
<html>
   <head>
       <title>Nodejs running ch00home01html</title>
   </head>
   <body>
       <h1>Nodejs running ch00home01.html</h1>
   </body>
</html>


檔案名稱:ch00test.html
檔案內容:
<html>
   <head>
       <title>Nodejs running ch00testhtml</title>
   </head>
   <body>
       <h1>Nodejs running ch00test.html</h1>
   </body>
</html>

檔案名稱:ch00config.js
檔案內容:
const config = {
    HostName:'127.0.0.1',
    PortName:'9000'
};
exports.config = config;


檔案名稱:ch00server.js
檔案內容:
const http = require('http');
const config = require('./ch00config').config;
const fs = require('fs');
 
const server = http.createServer((req,res) => {
          switch(req.url) {
            case '/':
               fs.readFile(__dirname + '/ch00index.html','utf-8',function (err,data){
                  if (err) {
                    res.setHeader('Content-Type','text/plain');
                    res.statusCode = 404;
                    res.end('Not Founded.');
                  } else {
                    res.setHeader('Content-Type','text/html');
                    res.statusCode = 200;
                    res.end(data);
                  }
                });  
               break;
            case '/home':
               fs.readFile(__dirname + '/ch00home01.html','utf-8',function (err,data){
                  if (err) {
                    res.setHeader('Content-Type','text/plain');
                    res.statusCode = 404;
                    res.end('Not Founded.');
                  } else {
                    res.setHeader('Content-Type','text/html');
                    res.statusCode = 200;
                    res.end(data);
                  }
                });
               break;
            case '/test':
               fs.readFile(__dirname + '/ch00test.html','utf-8',function (err,data){
                  if (err) {
                    res.setHeader('Content-Type','text/plain');
                    res.statusCode = 404;
                    res.end('Not Founded.');
                  } else {
                    res.setHeader('Content-Type','text/html');
                    res.statusCode = 200;
                    res.end(data);
                  }
                });
               break;
             default:
                    res.setHeader('Content-Type','text/plain');
                    res.statusCode = 404;
                    res.end('Not Founded.');
          }
});

server.listen(config.PortName,config.HostName,()=>{
    console.log(`Server running at http://${config.HostName}:${config.PortName}/`);
});

4.使用npm管理ejs(effective javascript templating)

(1)npm安裝ejs
    $npm install ejs

(2)運行ejs
檔案名稱:ch06config.js
檔案內容:
const config = {
    HostName:'127.0.0.1',
    PortName:'9000'
};
exports.config = config;

檔案:ch10index.ejs
內容:
<html>
       <title><%= title %></title>
       <body>
             <%- content %>
       </body>
</html>

檔案:ch10server.js
內容:
const http = require('http');
const fs = require('fs');
const config = require('./ch06config').config;
const ejs = require('ejs');
var template = fs.readFileSync(__dirname + '/ch10index.ejs','utf-8');

const server = http.createServer((req,res) => {
     var data = ejs.render(template,{
         title:'ch10index ejs',
         content:'<h1><strong>big ch10index ejs.</strong></h1>'
     });
     res.setHeader('Content-Type','text/html');
     res.statusCode = 200;
     res.end(data);
});
server.listen(config.port,config.hostname,() =>{
    console.log(`Server running at http://${config.hostname}:${config.port}/`);
});

5.利用外部文件ch06config.js 與ch11index.ejs,做個簡單的公告系統

檔案名稱:ch06config.js
檔案內容:
const config = {
    hostname:'127.0.0.1',
    port:'3000'
};
exports.config = config;

檔案名稱:ch11index.ejs
檔案內容:
<!DOCTYPE html>
<html lang="zh-hans">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title><%- title %></title>
  </head>
  <body>
   <form action="" method="POST">
     <input type="text" name="content" id="content">
     <input type="submit" value="submit">
     <ul>
       <% for( var i = 0 ; i < posts.length ; i++) { %>
         <li><%= posts[i] %></li>
       <% } %>
     </ul>
   </form>
  </body>
</html>

檔案名稱:ch11server.js
檔案內容:
const http = require('http');
const fs = require('fs');
const ejs = require('ejs');
const qs = require('querystring');
const config = require('./ch06config').config;

var template = fs.readFileSync(__dirname+'/ch11index.ejs','utf-8');
var posts = [];

const server = http.createServer((req,res)=>{
//  res.setHeader('Content-Type', 'text/html');
//  res.statusCode = 200;
//  res.end('OK');
  if (req.method === 'POST') {
    req.data = "";
    req.on("readable",function(){
      var chr =req.read();
      if (chr) {
        req.data +=chr;
      }
    });
    req.on("end",function () {
      var query = qs.parse(req.data);
      posts.push(query.content);
      showForm(posts,res);
    });
  } else {
    showForm(posts,res); 
  }
   
});

server.listen(config.port,config.hostname,()=>{
   console.log(`Server running at http://${config.hostname}:${config.port}/`);
});

function showForm(p_posts,res) {
  var data = ejs.render(template,{
      title:"TEST",
      posts:p_posts
  });
  res.setHeader('Content-Type','text/html');
  res.statusCode = 200;
  res.write(data);
  res.end(`Server running at http://${config.hostname}:${config.port}/`);
}

6.連接Mongodb

(1)安裝mongodb
$sudo apt-get install mongodb

(2)檢查版本
$mongo -version

(3)mongodb 啟動、關閉與重啟
$service mongodb start
$service mongodb stop
$service mongodb restart

(4)建立TestDB
$mongo
>use TestDB

(5)安裝mongodb driver
$npm install mongodb

(6)建立ch12mongofunc.js
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

//connect url
const url = 'mongodb://127.0.0.1:27017';

//Database Name
const dbName = 'TestDB';

//Use connect method to connect to the server
MongoClient.connect(url,function(err,client){
    console.log(err);
    assert.equal(null,err);
    console.log("Connected successfully to server");
    const db = client.db(dbName);
    client.close();
});

7.將資料插入mongodb的TestDB內

(1)修改步驟6的ch12mongofunc.js
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

//connect url
const url = 'mongodb://127.0.0.1:27017';

//Database Name
const dbName = 'TestDB';

//Use connect method to connect to the server
MongoClient.connect(url,function(err,client){
    assert.equal(null,err);
    console.log("Connected successfully to server");
    const db = client.db(dbName);

   db.collection("posts",function(err,collection){
      var list = [
        {title: "Mongodb connectted successfully01", tag: "Good01!" },
        {title: "Mongodb connectted successfully02", tag: "Good02!" },
        {title: "Mongodb connectted successfully03", tag: "Good!03" }
      ];
      collection.insert(list,function(err,result){
        console.log(err);
        console.log(result);
        assert.equal(null,err);
        client.close();
      });
   });
});
運行結果:
資料庫:

8.將mongodb之TestDB內資料列出

(1)修改步驟6的ch12mongofunc.js
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

//Connection URL
const url = 'mongodb://127.0.0.1:27017'

//Database Name
const dbName = 'testlog';

//use connect method to connect to the server
MongoClient.connect(url,function (err,client) {
   assert.equal(null,err);
   console.log("Connected successfully to server");
   
   const db = client.db(dbName);

   db.collection("posts",function(err,collection){
      collection.find({tag:"Good01!"}).toArray(function(err,result){
        console.log(err);
        assert.equal(null,err);
        console.log(result);
        client.close();
      });
   });
});
運行結果:

資料庫:

9.Callback函數無窮Callback 與解決方案

狀況說明:下面檔案寫法OK(可執行),但是可讀性很差。
檔案名:ch16callbackfun01.js
內容:
function callbackfun(sql,done) {
  setTimeout(() => done(sql + " update ok!"),1000);
}
callbackfun("01.sql",done => {
  console.log(done);
  callbackfun("02.sql", done => {
    console.log(done);
    callbackfun("03.sql", done => {
      console.log(done);
    });
  });
});

解決方案1:
檔案名:ch16callbackfun02.js
內容:
function ch16callbackfunAsync(sql) {
  const p = new Promise((resolve,reject) =>{
    setTimeout(()=>{
      console.log(sql +" update ok!");
      resolve(sql+".ok!");
    },1000);
  });
  return p;
}

ch16callbackfunAsync("1.sql")
                .then(()=>ch16callbackfunAsync("2.sql"))
                .then(()=>ch16callbackfunAsync("3.sq1"));

解決方案2:
檔案名:ch16callbackfun03.js
內容:
function ch16callbackfunAsync(sql) {
  const p = new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log(sql + " update ok!");
      resolve(sql + ".ok!");
    }, 1000);
  });
  return p;
}

async function ch16callbackAllfun() {
    const result01 = await ch16callbackfunAsync("1.sql");
    const result02 = await ch16callbackfunAsync("2.sql");
    const result03 = await ch16callbackfunAsync("3.sql");
    console.log(result01,result02,result03);
}
ch16callbackAllfun();


資料來源:
1.Node.js入門
2.小馬/Node.js入門
3.npm官網
4.ejs官網
5.MongoDB Node.JS Driver
6.Ubuntu下MongoDB的安装和使用
7.Day18 - Node.JS 串接 MongoDB (含CRUD) 

沒有留言:

張貼留言

在 Windows 10 x64 1909版,使用BAT快速安裝公文系統與人事服務網(自然人憑證)版

相關內容移往 https://skjhcreator.blogspot.com/2021/02/windows-10-x64-1909bat.html