以流的概念html
步驟前端
pipenode
代碼 const zlib = require( 'zlib' ) // zlib是一個壓縮包的內置模塊 const fs = require( 'fs' ) // fs是文件系統 const inp = fs.createReadStream('./dist/1.txt') // 建立可讀的流 const out = fs.createWriteStream('1.txt.gz') //建立可寫的流 const gzib = zlib.createGzip() // 建立一個空的壓縮包 inp .pipe( gzib ) .pipe( out ) $ node 文件名
console模塊web
經過後端語言爬取網站中的數據,而後經過特定模塊進行數據清洗,最後將數據輸出到前端json
不是全部的網站都能爬取後端
基本組成app
程序入口網站
請求模塊ui
這邊用的是get,代碼以下: const http = require( 'http' ); const cheerio = require( 'cheerio' ); http.get('http://nodejs.org/dist/index.json', (res) => { const { statusCode } = res; // 獲取狀態碼 1xx - 5xx const contentType = res.headers['content-type']; // 文件類型 text/json/html/xml let error; // 錯誤報出,狀態碼不是200,報錯,不是json類型報錯 if (statusCode !== 200) { error = new Error('Request Failed.\n' + `Status Code: ${statusCode}`); } else if (!/^application\/json/.test(contentType)) { error = new Error('Invalid content-type.\n' + `Expected application/json but received ${contentType}`); } if (error) { console.error(error.message); // consume response data to free up memory res.resume(); // 繼續請求 return; } res.setEncoding('utf8'); // 字符編碼
option裏分別寫入爬取網址的數據和請求頭數據this
若是是html格式的,如下代碼能夠不用寫
let error; // 錯誤報出,狀態碼不是200,報錯,不是json類型報錯 if (statusCode !== 200) { error = new Error('Request Failed.\n' + `Status Code: ${statusCode}`); } else if (!/^application\/json/.test(contentType)) { error = new Error('Invalid content-type.\n' + `Expected application/json but received ${contentType}`); } if (error) { console.error(error.message); // consume response data to free up memory res.resume(); // 繼續請求 return; }
-數據解釋
將爬取到的數據調用cheerio顯示或保存
res.setEncoding('utf8'); // 字符編碼 // 核心 -- start let rawData = ''; res.on('data', (chunk) => { rawData += chunk; }); // 數據拼接 res.on('end', () => { // 數據獲取結束 try { const $ = cheerio.load( rawData ) $('td.student a').each( function ( item ) { console.log( $( this ).text() ) }) } catch (e) { console.error(e.message); } }); // 核心 -- end }).on('error', (e) => { console.error(`Got error: ${e.message}`); }); req.end()