Home >Web Front-end >JS Tutorial >Nodejs code snippets you will definitely collect_node.js

Nodejs code snippets you will definitely collect_node.js

WBOY
WBOYOriginal
2016-05-16 15:16:091666browse

The following are four Nodejs code snippets worth collecting for your reference. The specific content is as follows

1. For information about static resource compression and caching in Nodejs, see: Nodejs Building Static Resource Server and File Upload. When I first learned Express, I couldn’t find a suitable method for gzip compression of dynamic files for a long time, only to realize that this is it. Simple...
Add compression module to app.js:
Install first; var compress=require('compression');app.use(compress()); OK, dynamic files can also be gzip compressed;

2. Grab girls’ pictures:

//依赖模块
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. Unzip the file

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. Compressed file

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");
 });
});

The above is the entire content of this article. I hope it will be helpful to everyone’s study. Let’s make progress together in the new year!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn