事件 events 模塊
原生事件寫法
/* * 1. 事件分類 * DOM0級 事件 - on + eventType * DOM2級 事件 - 事件監(jiān)聽 * 2. 事件構(gòu)成部分有哪些? dom.onclick = function () {} * 事件源 * 事件類型 click change ... * 事件處理程序 * 3. 事件綁定形式有哪些? * dom.onclick = function () {} * 事件監(jiān)聽 dom.addEventListener('click',function(){},false) * 元素綁定 <div onclick = "load()"></div> */
Node.js 事件驅(qū)動
問題: Node.js中有DOM嗎?
創(chuàng)建了一個叫做 events 內(nèi)置模塊來解決這個問題
const events= require('events');//events.EventEmitter//構(gòu)造函數(shù)console.log(events.EventEmitter.prototype)//原型鏈/* EventEmitter { _events: undefined, _eventsCount: 0, _maxListeners: undefined, setMaxListeners: [Function: setMaxListeners], getMaxListeners: [Function: getMaxListeners], emit: [Function: emit], addListener: [Function: addListener], on: [Function: addListener], prependListener: [Function: prependListener], once: [Function: once], prependOnceListener: [Function: prependOnceListener], removeListener: [Function: removeListener], off: [Function: removeListener], removeAllListeners: [Function: removeAllListeners], listeners: [Function: listeners], rawListeners: [Function: rawListeners], listenerCount: [Function: listenerCount], eventNames: [Function: eventNames] }*/const archetype=events.EventEmitter.prototype;// archetype.on(事件,事件處理函數(shù)) 作用發(fā)布// archetype.emit(事件名,實際參數(shù)) 作用訂閱archetype.on('handler',(val)=>{console.log('事件觸發(fā)',val);})archetype.emit('handler',111)
Readline模塊逐行讀取文本內(nèi)容
readline 模塊提供了一個接口,用于一次一行地讀取可讀流(例如 process.stdin)中的數(shù)據(jù)。
const readline = require('readline');const rl = readline.createInterface({ input: process.stdin, output: process.stdout});rl.question('你如何看待 Node.js 中文網(wǎng)?', (answer) => { // TODO:將答案記錄在數(shù)據(jù)庫中。 console.log(`感謝您的寶貴意見:${answer}`); rl.close();});
const readline = require('readline');const fs = require('fs');const rl = readline.createInterface({ input: fs.createReadStream('sample.txt')});rl.on('line', (line) => { console.log('Line from file:', line);});
簡易爬蟲
/* * 爬蟲 * 1. 進(jìn)行數(shù)據(jù)請求,獲取網(wǎng)頁內(nèi)容 http * 2. 進(jìn)行數(shù)據(jù)分析、數(shù)據(jù)清洗 * 3. 發(fā)送給我們自己的網(wǎng)頁*/
const http=require('http')//獲取 JSON 的示例:http.get('http://jsonplaceholder.typicode.com/albums', (res) => { /* res就是我得到的返回值 */ const { statusCode } = res;//狀態(tài)碼 const contentType = res.headers['content-type'];//得到的文件類型// 錯誤代碼處理 let error; if (statusCode !== 200) { error = new Error('請求失敗\n' + `狀態(tài)碼: ${statusCode}`); } else if (!/^application\/json/.test(contentType)) { error = new Error('無效的 content-type.\n' + `期望的是 application/json 但接收到的是 ${contentType}`); } if (error) { console.error(error.message); // 消費響應(yīng)數(shù)據(jù)來釋放內(nèi)存。 res.resume();//重新發(fā)起數(shù)據(jù) return; } res.setEncoding('utf8');//中文編碼 let rawData = '';//真實數(shù)據(jù) res.on('data', (chunk) => { rawData += chunk; });// 通過data事件將數(shù)據(jù)分片,然后逐片添加到rawData身上,好處就是當(dāng)我們執(zhí)行每一個分片的小任務(wù)時,至少給其他任務(wù)提供了可執(zhí)行的機(jī)會 res.on('end', () => {//結(jié)束 try {// 高級編程 錯誤捕獲 const parsedData = JSON.parse(rawData); console.log(parsedData); } catch (e) { console.error(e.message); } });}).on('error', (e) => { console.error(`出現(xiàn)錯誤: ${e.message}`);});
const http=require('http');const cheerio=require('cheerio')const options={ hostname: 'jx.1000phone.net', port: 80, path: '/teacher.php/Class/classDetail/param/rqiWlsefmajGmqJhXXWhl3ZiZ2Zn', method: 'GET', headers: { Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7', 'Cache-Control': 'no-cache', Connection: 'keep-alive', Cookie: 'PHPSESSID=ST-117984-IVZSfYMlr9YXvRfFRm-A1TimOeA-izm5ejd5j1npj2pjc7i3v4z', Host: 'jx.1000phone.net', Pragma: 'no-cache', Referer: 'http://jx.1000phone.net/teacher.php/Class/index', 'Upgrade-Insecure-Requests': 1, 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36', 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': 0 }}http.get(options, (res) => { const { statusCode } = res; const contentType = res.headers['content-type']; res.setEncoding('utf8'); let rawData = ''; res.on('data', (chunk) => { rawData += chunk; }); res.on('end', () => { try {const $=cheerio.load(rawData);$('.student a').each(function(item,index){ console.log($(this).text()); }) } catch (e) { console.error(e.message); } });}).on('error', (e) => { console.error(`出現(xiàn)錯誤: ${e.message}`);});