以下就是為大家分享的四段Nodejs值得收集的程式碼片段,供大家參考,具體內容如下
1、關於Nodejs的靜態資源壓縮與快取參見:Nodejs打造靜態資源伺服器與文件上傳剛學Express那會,動態檔的gzip壓縮,好長一段時間都沒找到合適的方法,才發現就是這麼簡單…
app.js裡新增compression模組:
先安裝;var compress=require('compression');app.use(compress()); OK了動態檔案也能gzip壓縮了;
2、抓取妹子的圖片:
//依赖模块 var fs = require('fs'); var request = require("request"); var cheerio = require("cheerio"); var mkdirp = require('mkdirp'); //目标网址 var url = 'http://me2-sex.lofter.com/tag/美女摄影?page='; //本地存储目录 var dir = './images'; //创建目录 mkdirp(dir, function(err) { if(err){ console.log(err); } }); //发送请求 request(url, function(error, response, body) { if(!error && response.statusCode == 200) { var $ = cheerio.load(body); $('.img img').each(function() { var src = $(this).attr('src'); console.log('正在下载' + src); download(src, dir, Math.floor(Math.random()*100000) + src.substr(-4,4)); console.log('下载完成'); }); } }); //下载方法 var download = function(url, dir, filename){ request.head(url, function(err, res, body){ request(url).pipe(fs.createWriteStream(dir + "/" + filename)); }); };
3、解壓縮檔
var fs = require('fs'), unzip = require('unzip'); //fs.createReadStream('./angular-swipe-master.zip').pipe(unzip.Extract({ path: './' })); var extract = unzip.Extract({ path: './' }); extract.on('error', function(err) { console.log(err); }); extract.on('finish', function() { console.log("unziped!!"); }); fs.createReadStream('./angular-swipe-master.zip').pipe(extract);
4、壓縮檔
var fs = require("fs"); var zip = require("node-native-zip"); var archive = new zip(); archive.addFiles([ { name: "app.j", path: "./app.js" }, { name: "package.json", path: "./package.json" } ], function (err) { if (err) return console.log(err); var buff = archive.toBuffer(); fs.writeFile("./test2.zip", buff, function () { console.log("ziped"); }); });
以上就是本文的全部內容,希望對大家的學習有所幫助,在新的一年裡我們共同進步!