Details about Node. js serialization Process Control and node. js serialization

Source: Internet
Author: User

Details about Node. js serialization Process Control and node. js serialization

Serial task: the task that needs to be followed is called a serial task.

You can use the callback method to execute several asynchronous tasks in sequence. However, if there are too many tasks, you must organize them. Otherwise, excessive callback nesting will mess up the code.

To implement several asynchronous tasks in sequence with serialized process control, you need to put these tasks in an array in the expected execution order. This array will act as a queue: after a task is completed, the next one is taken from the array in sequence.

Each task in the array is a function. After the task is completed, a processor function should be called to tell it the error status and result.

To demonstrate how to implement serialized process control, we are going to create a small program to get the title and URL of an article from a randomly selected RSS pre-source and display it.

You need to download two auxiliary modules from the npm storage, and enter the following command in the command line (taking the mac system as an example:

mkdir random_storycd random_storynpm install requestnpm install htmlparser

The request module is a simplified HTTP client that can obtain RSS data. The htmlparser module can convert original RSS data into JavaScript data structures.

Create a random_story.js file in the new directory, which contains the following code:

Var fs = require ('fs'); var request = require ('request'); var htmlparser = require ('htmlparser '); var configFilename = '. /rss_feeds.txt '; // ensure that the file containing the RSS subscription list contains function checkForRSSFile () {fs. exists (configFilename, function (exists) {if (! Exists) {return next (new Error ('missing RSS file: '+ configFilename);} next (null, configFilename );});} // read and parse the file function readRSSFile (configFilename) {fs. readFile (configFilename, function (err, feedList) {if (err) {return next (err);} feedList = feedList. toString (). replace (/^ \ s + | \ s + $/g ,''). split ("\ n"); var random = Math. floor (Math. random () * feedList. length); next (null, feedList [rando M]);} // send an HTTP request to the source to obtain the data function downloadRSSFeed (feedUrl) {request ({uri: feedUrl}, function (err, res, body) {if (err) {return next (err);} if (res. statusCode! = 200) {return next (new Error ('Abnormal response status Code');} next (null, body );});} // parse the function parseRSSFeed (rss) {var handler = new htmlparser. rssHandler (); var parser = new htmlparser. parser (handler); parser. parseComplete (rss); if (! Handler. dom. items. length) {return next (new Error ('no RSS items found. ');} var item = handler. dom. items. shift (); console. log (item. title); console. log (item. link);} var tasks = [checkForRSSFile, readRSSFile, downloadRSSFeed, parseRSSFeed]; function next (err, result) {if (err) {throw err;} var currentTask = tasks. shift (); if (currentTask) {currentTask (result) ;}// start to execute the serialization task next ();

Before creating this program, you can create an rss_feeds.txt file in the script directory. Only one predefined source information is contained here:

http://dave.smallpict.com/rss.xml

Then run the script:

node random_story.js

The returned information is as follows. A serialized process control is successfully implemented.

[Serial Process Control in async/await format]

Then, rewrite the source code to the async/await form of ES7. The level is limited. If there is an error, please point it out!

let fs = require('fs');let request = require('request');let htmlparser = require('htmlparser');let configFilename = './rss_feeds.txt';function checkForRSSFile() {  return new Promise((resolve, reject) => {    fs.exists(configFilename, (exists) => {      if (!exists) {        reject(new Error('Missing RSS file: ' + configFilename));      }      resolve();    });  });}function readRSSFile(configFilename) {  return new Promise((resolve, reject) => {    fs.readFile(configFilename, (err, feedList) => {      if (err) {        reject(err);      }      feedList = feedList.toString().replace(/^\s+|\s+$/g, '').split("\n");      let random = Math.floor(Math.random()*feedList.length);      resolve(feedList[random]);    });  });}function downloadRSSFeed(feedUrl) {  return new Promise((resolve, reject) => {    request({uri: feedUrl}, (err, res, body) => {      if (err) {        reject(err);      }      if (res.statusCode !== 200) {        reject(new Error('Abnormal response status code'));      }      resolve(body);    });  });}function parseRSSFeed(rss) {  let handler = new htmlparser.RssHandler();  let parser = new htmlparser.Parser(handler);  parser.parseComplete(rss);  if (!handler.dom.items.length) {    throw new Error('No RSS items found.');  }  let item = handler.dom.items.shift();  console.log(item.title);  console.log(item.link);}async function getRSSFeed() {  await checkForRSSFile();  let url = await readRSSFile(configFilename);  let rss = await downloadRSSFeed(url);  return rss;}getRSSFeed().then(rss => parseRSSFeed(rss), e => console.log(e));

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.