一、Api模塊
1轧拄、內(nèi)置模塊
- os 操作系統(tǒng)
- path 路徑
- fs 文件讀寫
const fs = require('fs')
fs.stat('hello.js', (err, stats) => {
if(error){
console.log(err)
} else {
console.log(stats)
console.log('文件:' + stats.isFile())
console.log('目錄:' + stats.isDirectory())
}
})
fs.mkdir('log', (err) => {
if(err){
console.log(err)
} else {
console.log('成功創(chuàng)建完箩!')
}
})
fs.writeFile('log/hellos.js', 'console.log("writeFile")',(err) =>{
if(err){
console.log(err)
} else {
console.log('寫入成功')
}
})
// 追加內(nèi)容
fs.appendFile('log/hellos.js', 'console.log("writeFile")',(err) =>{
if(err){
console.log(err)
} else {
console.log('寫入成功')
}
})
fs.readFile('log/hellos.js', 'utf8', (err, data) =>{
if(err){
console.log(err)
} else {
console.log(data)
}
})
// 讀取文件列表
fs.readdir('log', (err, files) => {
if(err){
console.log(err)
} else {
console.log(files)
}
})
// [ 'hello.js' ]
fs.rename('log', 'logs', (err) =>{
if(err){
console.log(err)
} else {
console.log('修改名字成功飞蹂!')
}
})
// 刪除目錄
fs.readdirSync('logs').map(file =>{
fs.unlink(`logs/${file}`, (err) =>{
if(err){
console.log(err)
} else {
console.log('刪除文件: logs/' + file + '成功柄延!')
}
})
})
fs.rmdir('logs', (err) =>{
if(err){
console.log(err)
} else {
console.log('刪除成功!')
}
})
// 刪除文件
fs.unlink('hello.js', (err) =>{
if(err){
console.log(err)
} else {
console.log('成功刪除文件挎峦!')
}
})
- stream (大文件讀寫)
const fs = require('fs')
const fileReadStream = fs.createReadStream('data.json')
const fileWriteStream = fs.createWriteStream('data-1.json')
let count = 0
fileReadStream.on('once', (chunk) =>{
console.log(chunk.toString())
})
fileReadStream.on('data', (chunk) =>{
console.log(`第${++count}次接收到${chunk.length}`)
fileWriteStream.write(chunk)
})
fileReadStream.on('end', (chunk) =>{
console.log('結(jié)束香追!')
})
// 管道 pipe
const fs = require('fs')
const zlib = require('zlib') // gzip壓縮模塊
const fileReadStream = fs.createReadStream('data.json')
const fileWriteStream = fs.createWriteStream('data.json.gz')
fileWriteStream.on('pipe', (source) => {
console.log(source)
})
fileReadStream
.pipe(zlib.createGzip()) // 增加gzip壓縮過程
.pipe(fileWriteStream) // 讀取流寫入
- require 導入模塊
- url url解析
url.parse('https://www.baidu.com/') // 解析url,返回url對象
url.format() // 逆向parse
// resolve
url.resolve('/one/two/three', 'four'); // '/one/two/four'
url.resolve('http://example.com/', '/one'); // 'http://example.com/one'
url.resolve('http://example.com/one', '/two'); // 'http://example.com/two'
- querystring
// 正反序列化
querystring.parse("{name: 'sgr’, age: '26'}")
querystring.stringify({name: 'sgr’, age: '26'})
// 正反編碼
querystring.escape('北京')
querystring.unescape('%E5%8C%97%E4%BA%AC')
- htttp
const http = require('http')
const https = require('https')
const url = 'https://www.lagou.com/wn/'
https.get(url, function(res){
let html = ''
res.on('data', function(data){
html += data
})
res.on('end', function(){
console.log(html)
})
res.on('error', function(err){
console.log(err)
})
})
- https
// get請求
const https = require('https')
const options = {
hostname: 'api.douban.com',
port: 443,
path: '/v2/movie/top250',
method: 'GET'
};
let responseData = ''
const req = https.request(options, res => {
res.setEncoding('utf8')
res.on('data', function(html){
console.log('狀態(tài)碼:', res.statusCode);
responseData += html
})
res.on('end', function(){
console.log(JSON.parse(responseData))
})
res.on('error', function(error){
console.log(error);
})
})
request.on('error', function(){
})
request.end()
const https = require('https')
const querystring = require('querystring')
const postData = querystring.stringify({
title: 'css 外部文件如何引入',
content: '<p>css 外部文件如何引入</p>',
courseId: '227',
lessonId: '1753'
})
var options = {
hostname: 'www.baidu.com',
port: 80,
methods: 'POST',
path: '/ajax/create/course/question',
header: {
Accept: '*'
}
}
var responseData = ''
const request = https.request(options, (response) =>{
response.setEncoding('utf8')
response.on('data', res=> {
console.log(res)
})
response.on('end', res=> {
console.log('end')
})
})
request .on('error', function(){
console.log(error)
})
request .end()
- events
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', () => { // 用于注冊監(jiān)聽器
console.log('觸發(fā)了一個事件坦胶!');
});
myEmitter.emit('event'); // 用于觸發(fā)事件
2透典、三方模塊
- nodemon
熱更新模塊晴楔,更改代碼后執(zhí)行js - cheerio
node端的jquery
npm install cheerio
const cheerio = require('cheerio')
res.on('end', function(){
// console.log(html)
filterMenu(html)
})
function filterMenu(html){
const $ = cheerio.load(html)
let menu = $('.menu_box')
let menuData = []
menu.each(function(index, value){
const title = $(value).find('h2').text()
const lists = $(value).find('a')
const menuList = []
lists.each(function(index, value){
menuList.push($(value).text())
})
console.log(title, menuList)
})
}
- request
request({
url: 'https://api.douban.com/v2/movie/top250',
json: true
}, (err, response, bod) =>{
console.log(JSON.stringify(body, null, 2))
console.log(err, response, body)
})
- async
- async
// 串行 無關(guān)聯(lián) 數(shù)組
const async = require('async')
console.time('test')
async.series([
function (callback) {
setTimeout(() => {
callback(null, 'one')
}, 2000)
},
function (callback) {
setTimeout(() => {
callback(null, 'two')
}, 5000)
}
], function (err, result) {
console.log(err, result)
console.timeEnd('test') // test: 7017ms
})
// 串行 無關(guān)聯(lián) 對象
const async = require('async')
console.time('test')
async.series({
one: function (callback) {
setTimeout(() => {
callback(null, '1')
}, 1000)
},
two: function (callback) {
setTimeout(() => {
callback(null, '2')
}, 3000)
}
}, function (err, result) {
console.log(err, result)
console.timeEnd('test')
})
// 并行 無關(guān)聯(lián) 數(shù)組
const async = require('async')
console.time('test')
async.parallel([
function (callback) {
setTimeout(() => {
callback(null, 'one')
}, 2000)
},
function (callback) {
setTimeout(() => {
callback(null, 'two')
}, 5000)
}
], function (err, result) {
console.log(err, result)
console.timeEnd('test') // test: 7017ms
})
// 串行 有關(guān)聯(lián)
const async = require('async')
console.time('test')
async.waterfall([
function(callback){
callback(null, 'one', 'two');
},
function(arg1, arg2, callback){
console.log('arg1 => ' + arg1);
console.log('arg2 => ' + arg2);
callback(null, 'three');
},
function(arg3, callback){
console.log('arg3 => ' + arg3);
callback(null, 'done');
}
], function (err, result) {
console.log('err => ' + err);
console.log('result => ' + result);
})
3、自定義模塊
const helle = () => {
console.log('hello~')
}
module.exports.hello = hello
const greeting = require('./src/greeting.js')
greeting.hello()
二峭咒、Node創(chuàng)建后端路由
- 創(chuàng)建服務器
const http = require('http')
const url = require('url')
const router = require('./router')
http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'})
if(req.url !== '/favicon.ico'){
var pathname = url.parse(req.url).pathname
console.log(pathname)
router[pathname](req, res)
}
res.end()
}).listen(8000)
console.log('Server running at http://localhost:8000/')
- supervisor // 熱更新服務器文件修改
npm install supervisor -g
supervisor server.js
- router.js
const file = require('./file')
module.exports = {
home: function(req, res){
res.write('首頁')
},
login: function(req, res){
res.write('登錄')
},
image: function(req, res){
res.writeHead(200, {'Content-Type': 'image/jpeg'})
file.readImg('./images/1.jpeg', res)
},
register: function(req, res){
res.write('注冊')
}
}
- file.js
var fs = require('fs')
module.exports = {
readImg: function(file, res){
fs.readFile(file, 'binary', (err, data) => {
if(err)throw err;
res.writeHead(200, {'Content-Type': 'image/jpeg'})
res.write(data, 'binary')
res.end()
})
}
}
- 讀取圖片
var http = require('http')
const url = require('url')
const router = require('./js/router')
const file = require('./js/file')
http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'})
// res.writeHead(200, {'Content-Type': 'image/jpeg'})
if(req.url !== '/favicon.ico'){
let pathname = url.parse(req.url).pathname.slice(1)
console.log('pathname', pathname)
try{
router[pathname](req, res)
}catch(e){
router['home'](req, res)
}
}
}).listen(8000)
- 讀取文件和頁面
router.js
const file = require('./file')
module.exports = {
home: function(req, res){
file.readFile('./views/home.html', res, req)
},
login: function(req, res){
file.readFile('./views/login.html', res, req)
},
image: function(req, res){
res.writeHead(200, {'Content-Type': 'image/jpeg'})
file.readImg('./images/1.jpeg', res)
},
register: function(req, res){
file.readFile('./views/register.html', res, req)
}
}
file.js
var fs = require('fs')
module.exports = {
readFile: function(file, res, req){
console.log(5, file)
fs.readFile(file, 'utf-8', function(err, data){
if(err) throw err;
res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'})
res.write(data)
res.end()
})
},
readImg: function(file, res){
fs.readFile(file, 'binary', (err, data) => {
if(err)throw err;
res.writeHead(200, {'Content-Type': 'image/jpeg'})
res.write(data, 'binary')
res.end()
})
}
}
server.js
var http = require('http')
const url = require('url')
const router = require('./js/router')
const file = require('./js/file')
http.createServer(function(req, res){
if(req.url !== '/favicon.ico'){
let pathname = url.parse(req.url).pathname.slice(1)
console.log('pathname', pathname)
try{
router[pathname](req, res)
}catch(e){
router['home'](req, res)
}
}
}).listen(8000)
- 表單提交
router.js
const file = require('./file')
module.exports = {
home: function (req, res) {
file.readFile('./views/home.html', res, req)
},
login: function (req, res) {
let post = ''
req.on('data', function(chunk){
console.log(chunk)
post += chunk
})
req.on('end', function(){
file.postReadFile('./views/login.html', res, req, post)
})
},
image: function (req, res) {
res.writeHead(200, { 'Content-Type': 'image/jpeg' })
file.readImg('./images/1.jpeg', res)
},
register: function (req, res) {
file.readFile('./views/register.html', res, req)
}
}
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
登錄
<div>Email: {email}, 密碼:{password}</div>
<form action="./login" method="post">
<label for="email">
E-mail: <input type="text" name="email" value="" />
</label>
<label for="password">
密碼: <input type="password" autocomplete name="password" value="" />
</label>
<label for="submit">
<input type="submit" value="提交" />
</label>
</form>
</body>
</html>
file.js
var fs = require('fs')
var querystring = require('querystring')
module.exports = {
postReadFile: function (file, res, req, post) {
var urlObject = querystring.parse(post)
var array = ['email', 'password']
var reg;
fs.readFile(file, 'utf-8', function (err, data) {
console.log('data', data)
if (err) throw err;
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' })
for (let i = 0; i < array.length; i++) {
reg = new RegExp('{' + array[i] + '}', 'gi')
data = data.replace(reg, urlObject[array[i]])
}
console.log('data', data)
res.write(data)
res.end()
})
}
}
三税弃、簡易聊天功能
- socket版本
socketClient.js
var net = require('net')
var port = 9000
var host = '127.0.0.1'
var client = new net.Socket()
client.setEncoding = 'UTF-8'
client.connect(port, host, function(){
client.write('您好')
})
client.on('data', function(data){
console.log('服務端傳來:' + data);
say()
})
client.on('error', function(err){
console.log('err:', err)
})
client.on('close', function(){
console.log('connection closed')
})
const readline = require('readline')
const r1 = readline.createInterface({
input: process.stdin,
output: process.stdout
})
function say(){
r1.question('請輸入:', inputStr => {
if(inputStr != 'bye'){
client.write(inputStr + '\n')
} else {
client.distory()
}
})
}
socketServer.js
var net = require('net')
var chatServer = net.createServer(),
clientMap = new Object()
var i = 0 // 連接名稱的流水號
chatServer.on('connection', function(client){
console.log('客戶端有人鏈接')
client.name = ++i
clientMap[client.name] = client
// 對客戶端發(fā)送消息的監(jiān)聽
client.on('data', function(data){
console.log('客戶端傳來:' + data)
broadcast(data, client)
})
client.on('error', function(e){
console.log('client error:' + e)
client.end()
})
client.on('close', function(data){
delete clientMap[client.name]
console.log(client.name + "下線")
broadcast(client.name + '下線了', client)
})
})
// 消息廣播
function broadcast(message, client){
for(var key in clientMap){
clientMap[key].write(client.name + 'say: ' + message + '\n')
}
}
chatServer.listen(9000)
- ws版本
npm install ws
ws.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>WebSocket</h1>
<div id="chatroom" style="width:400px;height:300px;overflow:auto;border:1px solid blue;"></div>
<input type="text" name="sayinput" id="sayinput" value="">
<input type="button" name="send" id="sendbutton" value="發(fā)送">
<script src="WsClient.js" charset="utf-8"></script>
<script type="text/javascript">
function send() {
ws.send(sayinput.value)
sayinput.value = ''
}
document.onkeyup = function (event) {
if (event.keycode === 13) {
send()
}
}
sendbutton.onclick = function(){
send()
}
</script>
</body>
</html>
WsServer.js
var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({ port: 9000 })
var clientMap = new Object()
var i = 0
wss.on('connection', function (ws) {
console.log(ws + '上線')
ws.name = ++i
clientMap[ws.name] = ws
ws.on('message', function (message) {
broadcast(message, ws)
})
ws.on('close', function () {
// global.gc() // 調(diào)用內(nèi)存回收
console.log('回收')
})
})
function broadcast(msg, ws) {
for (var key in clientMap) {
clientMap[key].send(ws.name + '說:' + msg)
}
}
WsClient.js
var ws = new WebSocket('ws://127.0.0.1:9000')
ws.onopen = function () {
ws.send()
}
ws.onmessage = function (event) {
var chatroom = document.querySelector('#chatroom')
chatroom.innerHTML += '<br/>' + event.data
}
ws.onclose = function () {
alert('closed')
}
ws.onerror = function (err) {
alert('Error:' + err)
}
- socket.io版本
npm install express socket.io