Nodejs code snippets that you're sure to collect

  • 2020-12-18 01:43:43
  • OfStack

Here are 4 Nodejs code snippets worth collecting for your reference, as follows

1. Static resource compression and caching of Nodejs See: Nodejs Builds Static resource server and File Upload When I just learned Express, gzip compression of dynamic files did not find a suitable method for a long time, only to find that it was so simple...
app. Add compression module to js:
First installation; var compress=require('compression'); app.use(compress()); OK dynamic files can also gzip compression;

2. Grab pictures of girls:


// Rely on the module 
var fs = require('fs');
var request = require("request");
var cheerio = require("cheerio");
var mkdirp = require('mkdirp');
 
// The target site 
var url = 'http://me2-sex.lofter.com/tag/ The beauty of photography ?page=';
 
// Local storage directory 
var dir = './images';
 
// Create a directory 
mkdirp(dir, function(err) {
 if(err){
  console.log(err);
 }
});
 
// Send the request 
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(' Is downloading ' + src);
   download(src, dir, Math.floor(Math.random()*100000) + src.substr(-4,4));
   console.log(' The download is complete ');
  });
 }
});
 
// Download method 
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. Compress files


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

Above is the whole content of this article, I hope to help you in your study, in the New Year we make progress together!


Related articles: