Nodejs code snippets that you will definitely add to your favorites
The following are the four node. js code snippets worth collecting for your reference. The specific content is as follows:
1. For details about node. js static resource compression and caching, refer to: node. js creates a static resource server and uploads files to learn Express. the gzip compression of dynamic files has not been found for a long time, it's just that simple ......
Add the compression module to app. js:
Install it first; var compress = require ('compression'); app. use (compress (); dynamic files can also be compressed by gzip if OK;
2. Capture pictures of sisters:
// Dependent module var fs = require ('fs'); var request = require ("request"); var cheerio = require ("cheerio "); var mkdirp = require ('mkdirp '); // target url var url = 'HTTP: // me2-sex.lofter.com/tag/female photography? Page = '; // local storage directory var dir = '. /images '; // create the directory mkdirp (dir, function (err) {if (err) {console. log (err) ;}}); // send the request (url, function (error, response, body) {if (! Error & response. statusCode == 200) {var $ = cheerio. load (body); $ ('. img '). each (function () {var src = $ (this ). attr ('src'); console. log ('Download' + src); download (src, dir, Math. floor (Math. random () * 100000) + src. substr (-4, 4); console. log ('Download completed ') ;}}}); // download method var download = function (url, dir, filename) {request. head (url, function (err, res, body) {request (url ). pipe (fs. createWriteStream (dir + "/" + filename ));});};
3. decompress 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. File compression
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 all the content of this article. I hope it will help you learn and make progress together in the new year!
Articles you may be interested in:
- Nodejs extension code
- Node. js module writing entry (instance code)
- Sample Code for interaction between NodeJS and Mysql
- Use nodejs to implement the print_r Function Code of PHP
- Code for nodejs to obtain the Intranet and Internet IP addresses of the Local Machine
- Nodejs paging code sharing
- Easy creation of nodejs servers (3): Code Modularization
- NodeJS code is suitable for implementing calculation and social security