Nodejs Practical Learning Pen meter (turn)

Source: Internet
Author: User
Tags set time

I. Use NodeJS to complete timed tasks

Timed tasks: In a certain period of time, let the program do some tasks on its own, without the need to manually complete the manual.

Well, for example, I'm going to do a function of sending a syslog message to my client 8 o'clock in the morning every day. Well, this time you need a timed task device.

Later looked for a bit, found that node-schedule is not bad. It's easy to do my job:

// introduction of Node-schedule var schedule = require (' Node-schedule '); // Initialize and set time for scheduled Tasks var New  = a; // deal with the things to be done var function () {    console.log (' I've dealt with something here ... ');});

Https://github.com/tejasmanohar/node-schedule

Ii. using NodeJS to send mail

e-Mail can be said to be a very common function, for me, in php , or java in the realization of a rather difficult. However, in the NodeJS, it seems too simple.

A very common component that makes it Nodemailer easy for me to implement features:

varNodemailer = require ("Nodemailer");//here is the initialization, need to define the protocol sent, as well as your service mailbox, of course, including the passwordvarSmtptransport = Nodemailer.createtransport ("SMTP", {service:"Gmail", auth: {User:"[Email protected]", pass:"Userpass"    }});//mail Configuration, send a sample of Unicode compliant content try it! varMailoptions ={from:"Fred Foo?",//Send AddressTo: "[email protected], [email protected].com",//Receive listSubject: "Hello?",//Message SubjectText: "Hello world?",//text contentHTML: "Hello world?"//HTML content}//Start sending mailSmtptransport.sendmail (Mailoptions,function(Error, response) {if(Error) {Console.log (error); }Else{Console.log ("Mail has been sent:" +response.message); }    //If you need additional SMTP protocols, you can close the current reply    //smtptransport.close ();});
http://www.nodemailer.com/Third, crawl Web page data using NodeJS

It sounds like a "reptile", yes. is to use NodeJS to crawl a Web page to get and filter valuable content, and then continue to crawl more pages, so loop back and feedback.

Simply thinking about how to do it can be divided into 2 steps:

Through "get" request, crawl Web source to local server;

varHTTP = require (' http ');varurl = "Http://www.baidu.com"; http.get (URL,function(res) {varSource = ""; //get web page code source via GET requestRes.on (' Data ',function(data) {Source+=data;    }); //get to the data source, we can manipulate the data!Res.on (' End ',function() {console.log (source); //This will output a lot of HTML code    });}). On (' Error ',function() {Console.log ("Get Data Error");});

Analyze the source code and filter the valuable content. How to parse the "html" code on the server side? Simple and convenient, especially the operating habits, I recommend the use cheerio .

var cheerio = require (' Cheerio '),// Here you can define the source we just crawled from above//  Source is actually a fragment of  $ = cheerio.load (source); // we can manipulate the server-side capture of the data like JQuery (' H2.title '). Text (' Hello there! ') ); $ (' H2 '). AddClass (' welcome ');
Https://github.com/cheeriojs/cheerio Four, solve NodeJS crawl GBK encoded data garbled

Why does it appear garbled, here is not introduced. Obviously, Nodejs support is UTF8, and we caught the data is GBK, of course, chaos. At this point, we need an intermediary to switch.

Well, it iconv-lite can help us complete the task:

varHTTP = require (' http ')varIconv = require (' Iconv-lite '));varurl = ' http://www.taobao.com ';//Let's say we crawl the GBK encoded content, and then we need to transcode it.Http.get (URL,function(res) {res.setencoding (' Binary '); varSource = ""; Res.on (' Data ',function(data) {Source+=data;    }); Res.on (' End ',function() {        varBUF =NewBuffer (source, ' binary '); varstr = Iconv.decode (buf, ' GBK '));        Console.log (str); //the output here will not be garbled.}). On ("Error",function() {Logger.error (' Get data error '); });});

Https://github.com/ashtuchkin/iconv-lite

V. Use NodeJS to queue a "data array" to complete a task

From what I crawled above, I got a lot of meaningful link addresses through this simple "crawler". So I deposited them in an array. The next step is to traverse the connection address in the data and crawl the meaningful page again.

Some of the features of NodeJS, such as concurrency, asynchrony, etc., are very useful. But here, I give myself a violation of the requirements of the rules, is to let the array inside the link one by one and sequentially to execute, like a queue. To make it easier for me to see the progress of the data.

How do you queue up for it? What if there is an asynchronous operation in the queue? Alas, it's just a pain in the balls. It's kind of like a workflow. Yes, I'm Async.js perfectly qualified.

varAsync = require (' async ');//the defined source datavarDataarr = [' 1 ', ' 2 ', ' 3 ', ' 4 '];//Let's say I'm just going to do every line plus 1 operation.//I'm using the async Foreachseries method here.Async.foreachseries (Dataarr,function(item, callback) {Console.log (' Output data: ' +item); SetTimeout (function() {Console.log (' Asynchronous invocation of content, then output: ' + Item + 1); Callback (NULL, item); }, Item.delay);},function(Err) {Console.log (' Complete, whether there is an error: ' +err);});//after running, the output data will be the following:////output data: 1//asynchronous invocation of the content, and then output: one//output data: 2//the contents of the asynchronous call, and then output://Output data: 3//the contents of the asynchronous call, and then output://output data: 4//the contents of the asynchronous call, and then output://complete, whether there is an error: null

Well, again sigh nodeJS strong, there are community contributions. Here is Async.js the project address:

Https://github.com/caolan/async

Vi. creating files and writing files using NodeJS

This function is actually very simple, the function that calls directly is fs good. See the API documentation for the file system.

varFS = require (' FS ');//Create a new hello.txt and write Hello world! to the fileFs.open (' Hello.txt ', ' W ', 0666,function(E, fd) {if(e) {Console.log (' Error message: ' +e); } Else{fs.write (FD,' Hello world! ', 0, ' UTF8 ',function(e) {if(e) {Console.log (' Error message: ' +e); } Else{fs.closesync (FD);    }        }); }});

The above article turns from http://www.zhanxin.info/nodejs/2013-11-04-nodejs-practical-study-notes.html, author "Palm"

Nodejs Practical Learning Pen meter (turn)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.