柚子快報(bào)激活碼778899分享:Node.js基礎(chǔ)
柚子快報(bào)激活碼778899分享:Node.js基礎(chǔ)
Nodejs中文文檔:http://nodejs.cn/learn/how-much-javascript-do-you-need-to-know-to-use-nodejs
1. 認(rèn)識Node.js
Node.js是一個(gè)javascript運(yùn)行環(huán)境。它讓javascript可以開發(fā)后端程序,實(shí)現(xiàn)幾乎其他后端語言實(shí)現(xiàn)的所有功能。Nodejs是基于V8引擎,V8是Google發(fā)布的開源JavaScript引擎,本身就是用于Chrome瀏覽器的js解釋部分
1.1. nodejs的特性
Nodejs語法完全是js語法,懂js基礎(chǔ)就可以學(xué)會(huì)Nodejs后端開發(fā)NodeJs超強(qiáng)的高并發(fā)能力,實(shí)現(xiàn)高性能服務(wù)器開發(fā)周期短、開發(fā)成本低、學(xué)習(xí)成本低
1.2. 瀏覽器環(huán)境vs node環(huán)境
Nodejs可以解析JS代碼(沒有瀏覽器安全級別的限制,提供很多系統(tǒng)級別的API),如:
文件的讀寫(File System)
const fs = require('fs');
fs.readFile('./a', 'utf-8', (err, content) => {
console.log(content);
}
進(jìn)程的管理(Process)
function main(argv) {
console.log(argv);
}
main(process.argv.slice(2));
網(wǎng)絡(luò)通信(HTTP/HTTPS)
const http = require("http");
http.createServer((req, res) => {
res.writeHead(200, {
"Content-Type": "text/plain"
});
res.write("hello");
res.end();
}).listen(3000);
2. 開發(fā)環(huán)境搭建
http://nodejs.cn/download/
3. 模塊、包、commpnJS
3.1. CommonJS和ES6 module區(qū)別
CommonJS 模塊輸出的是一個(gè)值的拷貝,ES6 模塊輸出的是值的引用。CommonJS 模塊是運(yùn)行時(shí)加載,ES6 模塊是編譯時(shí)輸出接口。CommonJS 模塊的require()是同步加載模塊,ES6 模塊的import命令是異步加載,有一個(gè)獨(dú)立的模塊依賴的解析階段。
3.2. CommonJS
commonjs 規(guī)范應(yīng)用于 nodejs 應(yīng)用中,在 nodejs 應(yīng)用中每個(gè)文件就是一個(gè)模塊,擁有自己的作用域,文件中的變量、函數(shù)都是私有的,與其他文件相隔離。
CommonJS暴露的方式:
let name = 'node';
let obj = {
name: 'node',
age: 18
}
function say() {
console.log('good');
}
exports.方法 || 屬性
exports.name = name;
exports.obj = obj;
exports.say = say;
require接收:
const receive = require('./src/utils.js');
console.log(recevie); // {name: 'node', obj: {name: 'node', age: 18}, say: [Function: say]}
module.exports.方法 || 屬性
module.exports.name = name;
module.exports.obj = obj;
module.exports.say = say;
module.exports = {方法, 屬性} 直接暴露出去一個(gè)對象,require接收到的也是一個(gè)對象
module.exports = {
name,
obj,
say
}
注意:只要使用第三種方式暴露,就會(huì)覆蓋前兩種方式
3.3. ES6 module
ES6 module的導(dǎo)出方式
export逐個(gè)導(dǎo)出
export let name = 'node';
export let obj = {
name: 'node',
age: 18
}
export function say() {
console.log('good');
}
接收
import {name, obj, say} from './utils.js';
export{ }直接導(dǎo)出一個(gè)對象
let name = 'node';
let obj = {
name: 'node',
age: 18
}
function say() {
console.log('good');
}
export {name, obj, say};
接收
import * as receive from './utils.js';
export default默認(rèn)導(dǎo)出 默認(rèn)導(dǎo)出一個(gè)對象,不支持對象解構(gòu)語法;接受時(shí)也是接收的一個(gè)對象
let name = 'node';
let obj = {
name: 'node',
age: 18
}
function say() {
console.log('good');
}
export default {
name,
obj,
say
};
接收
import receive from './utils.js';
4. 內(nèi)置模塊
4.1. http
const http = require('http');
// 創(chuàng)建本地服務(wù)器來從其接收數(shù)據(jù)
const server = http.createServer();
// 監(jiān)聽請求事件
server.on('request', (request, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
data: 'Hello World!'
}));
});
server.listen(8000);
4.1.1. 接口:jsonp
const http = require('http');
const url = require('url');
const app = http.createServer((req, res) => {
let urlObj = url.parse(req.url, true);
switch (urlObj.pathname) {
case '/api/user':
res.end(`${urlObj.query.cb}({"name": "gp145"})`);
break;
default:
res.end('404.');
break;
}
});
app.listen(8080, () => {
console.log('localhost:8080');
});
4.1.2. 跨域:cors
const http = require('http');
const url = require('url');
const querystring = require('querystring');
const app = http.createServer((req, res) => {
let data = '';
let urlObj = url.parse(req.url, true);
res.writeHead(200, {
'content-type': 'application/json;charset=utf-8',
'Access-Control-Allow-Origin': '*',
});
req.on('data', (chunk) => {
data += chunk;
});
req.on('end', () => {
responseResult(querystring.parse(data));
});
function responseResult(data) {
switch (urlObj.pathname) {
case '/api/login':
res.end(
JSON.stringify({
message: data,
})
);
break;
default:
res.end('404.');
break;
}
}
});
app.listen(8080, () => {
console.log('localhost:8080');
});
4.2. url
4.2.1. parse
const url = require('url');
const urlString = 'https://www.baidu.com:443/ad/index.html?id=8&name=mouse#tag=110';
const parsedStr = url.parse(urlString);
console.log(parsedStr);
Url {
protocol: 'https:',
slashes: true,
auth: null,
host: 'www.baidu.com:443',
port: '443',
hostname: 'www.baidu.com',
hash: '#tag=110',
search: '?id=8&name=mouse',
query: 'id=8&name=mouse',
pathname: '/ad/index.html',
path: '/ad/index.html?id=8&name=mouse',
href: 'https://www.baidu.com:443/ad/index.html?id=8&name=mouse#tag=110'
}
4.2.2. format
const url = require('url');
const urlObject = {
protocol: 'https:',
slashes: true,
auth: null,
host: 'www.baidu.com:443',
port: '443',
hostname: 'www.baidu.com',
hash: '#tag=110',
search: '?id=8&name=mouse',
query: { id: '8', name: 'mouse' },
pathname: '/ad/index.html',
path: '/ad/index.html?id=8&name=mouse',
};
const parsedObj = url.format(urlObject);
console.log(parsedObj); // https://www.baidu.com:443/ad/index.html?id=8&name=mouse#tag=110
4.2.3. resolve
const url = require('url');
const a = url.resolve('/one/two/three', 'four'); // ( 注意最后加/ ,不加/的區(qū)別 )
const b = url.resolve('http://example.com/', '/test/one');
const c = url.resolve('http://example.com/one', '/test/two');
console.log(a); // /one/two/four
console.log(b); // http://example.com/test/one
console.log(c); // http://example.com/test/two
4.3. querystring
4.3.1. parse
const querystring = require('querystring');
const qs = 'x=3&y=4';
const parsed = querystring.parse(qs);
console.log(parsed); // [Object: null prototype] { x: '3', y: '4' }
4.3.2. stringify
const querystring = require('querystring');
const qo = {
x: 3,
y: 4,
};
const parsed = querystring.stringify(qo);
console.log(parsed); // x=3&y=4
4.3.3. escape/unescape
const querystring = require('querystring');
const str = 'id=3&city=北京&url=https://www.baidu.com';
const escaped = querystring.escape(str);
console.log(escaped); // id%3D3%26city%3D%E5%8C%97%E4%BA%AC%26url%3Dhttps%3A%2F%2Fwww.baidu.com
const str1 =
'id%3D3%26city%3D%E5%8C%97%E4%BA%AC%26url%3Dhttps%3A%2F%2Fwww.baidu.com';
const unescaped = querystring.unescape(str);
console.log(unescaped); // id=3&city=北京&url=https://www.baidu.com
4.4. event
const EventEmitter = require('events');
class MyEventEmitter extends EventEmitter {}
const event = new MyEventEmitter();
event.on('study', (movie) => {
console.log(movie);
});
event.emit('study', 'node');
4.5. 文件操作
const fs = require('fs')
// 創(chuàng)建文件夾
fs.mkdir('./logs', (err) => {
console.log('done.')
})
// 文件夾改名
fs.rename('./logs', './log', () => {
console.log('done')
})
// 刪除文件夾
fs.rmdir('./log', () => {
console.log('done.')
})
// 寫內(nèi)容到文件里
fs.writeFile('./logs/log1.txt','hello',
// 錯(cuò)誤優(yōu)先的回調(diào)函數(shù)
(err) => {
if (err) {
console.log(err.message)
} else {
console.log('文件創(chuàng)建成功')
}
}
)
// 給文件追加內(nèi)容
fs.appendFile('./logs/log1.txt', '\nworld', () => {
console.log('done.')
})
// 讀取文件內(nèi)容
fs.readFile('./logs/log1.txt', 'utf-8', (err, data) => {
console.log(data)
})
// 刪除文件
fs.unlink('./logs/log1.txt', (err) => {
console.log('done.')
})
// 批量寫文件
for (var i = 0; i < 10; i++) {
fs.writeFile(`./logs/log-${i}.txt`, `log-${i}`, (err) => {
console.log('done.')
})
}
// 讀取文件/目錄信息
fs.readdir('./', (err, data) => {
data.forEach((value, index) => {
fs.stat(`./${value}`, (err, stats) => {
// console.log(value + ':' + stats.size)
console.log(value + ' is ' + (stats.isDirectory() ? 'directory' : 'file'))
})
})
})
// 同步讀取文件
try {
const content = fs.readFileSync('./logs/log-1.txt', 'utf-8')
console.log(content)
console.log(0)
} catch (e) {
console.log(e.message)
}
// 異步讀取文件:方法一
fs.readFile('./logs/log-0.txt', 'utf-8', (err, content) => {
console.log(content)
console.log(0)
})
console.log(1)
// 異步讀取文件:方法二
const fs = require("fs").promises
fs.readFile('./logs/log-0.txt', 'utf-8').then(result => {
console.log(result)
})
因?yàn)閖s是單線程的,node環(huán)境執(zhí)行的js代碼是服務(wù)器端代碼,所以,絕大部分需要在服務(wù)器運(yùn)行期反復(fù)執(zhí)行業(yè)務(wù)代碼的邏輯,必須使用異步代碼。 服務(wù)器啟動(dòng)時(shí),如果需要讀取配置文件,或結(jié)束時(shí)需要寫入到狀態(tài)文件時(shí),可以使用同步代碼,因?yàn)檫@些代碼只在啟動(dòng)和結(jié)束時(shí)執(zhí)行一次,不影響服務(wù)器正常運(yùn)行時(shí)的異步執(zhí)行。
4.6. stream流模塊
在Nodejs中,流是一個(gè)對象,我們只需要響應(yīng)流事件就可以了;data事件表示流的數(shù)據(jù)已經(jīng)可以讀取了;end事件表示這個(gè)流已經(jīng)到末尾無數(shù)據(jù)可讀了;error事件表示出錯(cuò)
const fs = require('fs');
// 打開一個(gè)流:
const rs = fs.createReadStream('sample.txt', 'utf-8');
// data事件可能會(huì)有多次,每次傳遞的chunk是流的一部分?jǐn)?shù)據(jù)
rs.on('data', function (chunk) {
console.log('DATA:')
console.log(chunk);
});
rs.on('end', function () {
console.log('END');
});
rs.on('error', function (err) {
console.log('ERROR: ' + err);
});
要以流的形式寫入文件,只需要不斷調(diào)用write()方法,最后以end()結(jié)束
const fs = require('fs');
const ws1 = fs.createWriteStream('output1.txt', 'utf-8');
ws1.write('使用Stream寫入文本數(shù)據(jù)...\n');
ws1.write('END.');
ws1.end();
pipe就像可以把兩個(gè)水管串成一個(gè)更長的水管一樣,兩個(gè)流可以串起來。一個(gè)readable流和一個(gè)writable流串起來后,所有的數(shù)據(jù)自動(dòng)從readable流進(jìn)入到writable流,這種操作就是pipe
const fs = require('fs')
const readstream = fs.createReadStream('./1.txt')
const writestream = fs.createWriteStream('./2.txt')
readstream.pipe(writestream)
用pipe()把一個(gè)文件流和另一個(gè)文件流串起來,這樣源文件的所有數(shù)據(jù)就自動(dòng)寫入到目標(biāo)文件中,所以,這就是一個(gè)復(fù)制文件的程序
4.7. zlib
const fs = require('fs')
const zlib = require('zlib')
const gzip = zlib.createGzip()
const readstream = fs.createReadStream('./note.txt')
const writestream = fs.createWriteStream('./note2.txt')
readstream.pipe(gzip).pipe(writestream)
4.8. crypto
crypto模塊提供了通用的加密和哈希算法
md5:用于給任意數(shù)據(jù)一個(gè)簽名,通常是十六進(jìn)制的字符串表示
const crypto = require('crypto');
const hash = crypto.createHash('md5'); // 也可傳入sha1,就表示計(jì)算SHA1
// 可任意多次調(diào)用update():
hash.update('Hello, world!');
hash.update('Hello, nodejs!');
console.log(hash.digest('hex'));
update()方法默認(rèn)字符串編碼為utf-8,也可以穿入buffer 2. Hmac算法:也是一種哈希算法,可以利用md5或sha1等哈希算法。不同的是,Hmac還需要一個(gè)密鑰
const crypto = require('crypto');
const hmac = crypto.createHmac('sha256', 'secret-key');
hmac.update('Hello, world!');
hmac.update('Hello, nodejs!');
console.log(hmac.digest('hex')); // 80f7e22570...
只要密鑰發(fā)生了變化,那么,同樣的輸入會(huì)得到不同的簽名。 3. AES:一種常用的對稱加密算法。加解密的密鑰相同。crypto需要自己封裝好函數(shù)來支持AES
const crypto = require("crypto");
// key,iv必須是16個(gè)字節(jié)
function encrypt (key, iv, data) {
let decipher = crypto.createCipheriv('aes-128-cbc', key, iv);
// decipher.setAutoPadding(true);
return decipher.update(data, 'binary', 'hex') + decipher.final('hex');
}
function decrypt (key, iv, crypted) {
crypted = Buffer.from(crypted, 'hex').toString('binary');
let decipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
return decipher.update(crypted, 'binary', 'utf8') + decipher.final('utf8');
}
5. 路由
5.1. 基礎(chǔ)
const fs = require("fs")
const path = require("path")
function render(res, path) {
res.writeHead(200, { "Content-Type": "text/html;charset=utf8" })
res.write(fs.readFileSync(path, "utf8"))
res.end()
}
const route = {
"/login": (req, res) => {
render(res, "./static/login.html")
},
"/home": (req, res) => {
render(res, "./static/home.html")
},
"/404": (req, res) => {
res.writeHead(404, { "Content-Type": "text/html;charset=utf8" })
res.write(fs.readFileSync("./static/404.html", "utf8"))
}
}
5.2. 獲取參數(shù)
get請求
"/api/login":(req,res)=>{
const myURL = new URL(req.url, 'http://127.0.0.1:3000');
console.log(myURL.searchParams.get("username"))
render(res,`{ok:1}`)
}
post請求
"/api/login": (req, res) => {
var post = '';
// 通過req的data事件監(jiān)聽函數(shù),每當(dāng)接受到請求體的數(shù)據(jù),就累加到post變量中
req.on('data', function (chunk) {
post += chunk;
});
// 在end事件觸發(fā)后,通過querystring.parse將post解析為真正的POST請求格式,然后向客戶端返回。
req.on('end', function () {
post = JSON.parse(post);
render(res, `{ok:1}`)
});
}
5.3. 靜態(tài)資源處理
function readStaticFile(req, res) {
const myURL = new URL(req.url, 'http://127.0.0.1:3000')
var filePathname = path.join(__dirname, "/static", myURL.pathname);
if (fs.existsSync(filePathname)) {
res.writeHead(200, { "Content-Type": `${mime.getType(myURL.pathname.split(".")[1])};charset=utf8` })
res.write(fs.readFileSync(filePathname, "utf8"))
res.end()
return true
} else {
return false
}
}
柚子快報(bào)激活碼778899分享:Node.js基礎(chǔ)
相關(guān)鏈接
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點(diǎn)和立場。
轉(zhuǎn)載請注明,如有侵權(quán),聯(lián)系刪除。