以下是程式碼的調整與註記:
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
檔案內容:
(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();
});
(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();
});
});
});
運行結果:
資料庫:
檔案內容:
<!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>
檔案內容:
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
$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內
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;
}
.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;
}
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)
沒有留言:
張貼留言