"Nodejs development Crypto Currency" Seven: app.js Interpretation of Entrance procedure

Source: Internet
Author: User

App.js Interpretation of Entrance procedure

At the time of this posting, the Bitcoin price ¥2873.95/$443.95. Why is a crypto currency designed so popular? Why did Microsoft, IBM and other giants enter? Why would a technician who tries to understand Bitcoin be deeply attracted? What's so tempting about it? "Nodejs development Crypto currency", let's explore the password behind it.

The Nodejs development crypto currency is designed to provide detailed development documentation for cryptocurrency (billion), involving all aspects of developing products using NODEJS, from front-end to back-office, server-to-client, PC-to-Mobile, IO-intensive to compute-intensive, centralized to de-centralized, encrypted and decrypted, Area chain, and other aspects. This series of articles, only start, no end ...

Billion book: Add new impetus to human creation! The code is completely open source and the article is free to share. Official website http://ebookchain.org

QQ Exchange Group: 185046161

Objective

In the Getting Started article section, we already know that Nodejs applications can eventually be merged into a single file that is split into multiple files for ease of development.

The file that was split is naturally the object of our focus, usually this file is App.js or server.js, as we call it 入口程序 .

Apparently, Ebookcoin used app.js. In this article, let's read the document and learn to study its overall architecture process.

Source

Address: Https://github.com/Ebookcoin/ebookcoin/blob/master/app.js

Class diagram

JS originally has no class, so its class diagram is not easy to handle, can only roughly give its association with other modules.

Interpretation

Read the code directly and see.

1. Configuration processing

Any application will provide some parameters. There are a number of options for handling these parameters. In general, however, it is often necessary to provide an ideal environment, the default configuration, while giving you a way to modify it yourself.

(1) Global default configuration

Typically, the default parameters are small and can be hardcoded into the code. But a more flexible approach is to use a separate file. The file is used here ./config.json to save the global configuration, such as:

{    "port"7000,    "address""0.0.0.0",    "serveHttpAPI": true,    "serveHttpWallet": true,    "version""0.1.1",    "fileLogLevel""info",    "consoleLogLevel""log",    "sharePort": true,    ...

When you use it, you just need require it. Source:

varrequire("./config.json"// app.js 4行

However, for flexibility, the default value usually allows the user to modify.

(2) Using commander components, introducing command-line Options

The previous article, which has been shared, commander is a nodejs third-party component (installed with NPM) and is often used to develop command-line tools that are extremely simple to use. Source:

//1 rowsvar program = require (' Commander ');//19 rowsProgram. Version (Packagejson.version).option('-C,--config <path> ',' Config file path ')    .option('-P,--port <port> ',' Listening port number ')    .option('-A,--address <ip> ',' Listening host name or IP ')    .option('-B,--blockchain <path> ',' Blockchain db path ')    .option('-X,--peers [peers ...] ',' peers list ')    .option('-L,--log <level> ',' Log level '). Parse (PROCESS.ARGV);

This allows you to add options such as when executing commands at the command line, such -c -p as:

node app.js8888

At this point, the option is program.port saved in the form of a manual modification:

39行if (program.port) {    appConfig.port = program.port;}

This is a common and simple way to handle the global configuration of Nodejs applications and is worth learning.

For more information, please read the previous section on commander components.

2. Abnormal capture

As we summarize in the first part, it 异常要捕捉 is very easy to see here how the code handles global exception handling.

Note : For domain modules that have not been advocated, this part of the code will be removed from subsequent updates, only to be understood here.

(1) using the uncaughtException catch process exception

// 65行process.on(‘uncaughtException‘function (err) {    // handle the error safely    logger.fatal(‘System error‘, { message: err.message, stack: err.stack });    process.emit(‘cleanup‘);});

(2) using domain modules to catch global exceptions

96require(‘domain‘).create();d.on(‘error‘function (err) {    logger.fatal(‘Domain master‘, { message: err.message, stack: err.stack });    process.exit(0);});d.run(function () {...

In addition, for each module, it also uses thedomain

415require(‘domain‘).create();d.on(‘error‘function (err) {scope.logger.fatal(‘domain ‘ + name, {message: err.message, stack: err.stack});});...
3. Module loading

This is the real focus, but read the code, found that everything is so clean lillol, there is no multilayer 回调 those 大坑 , in fact, the use of async process management components.

The whole use is carried out, and when it is loaded, it is async.auto 顺序调用 used to make it work in modules async.parallel parallel; When an error occurs, the cleanup is used async.eachSeries .

It is manually drawn, which shows the sequence of loading and running of each module from the code 103-438 lines. A UML diagram is used instead for specific code later.

In the next chapter, we also need to sort async out the components. Here, as long as you can guess the code intent, you don't have to worry too much about async usage. Below, read the relevant source code:

(1) Initial network

packages.jsonthe frame is seen from the inside Express . By the introduction of the previous section, you know that you must initialize in the entry procedure. How exactly is it called? The following code is clearly familiar.

Express is an important web development framework for NODEJS, where the network network is essentially an express-based Web application that is naturally 白皮书 propagated 基于Http协议 .

//215 rowsNetwork: [' config ', function (CB, scope) {    varExpress =require(' Express ');varApp = Express ();varServer =require(' http '). Createserver (APP);varIO =require(' Socket.io ') (server);if(scope.config.ssl.enabled) {varPrivatekey = Fs.readfilesync (Scope.config.ssl.options.key);varCertificate = fs.readfilesync (Scope.config.ssl.options.cert);varHTTPS =require(' https '). Createserver ({...

Description : This is a async.auto common method network used by any method that needs a callback (here is config ), put in this array, the last callback function ( function (cb, scope) {//code} ), can be cleverly called, such as: scope.config .

The code here, just initialize the service, does not do much of the real thing, the real action is below.

(2) Build links

Starting with the code below, we can see the nature of this application. 270 lines of code to use network , such as:

// 270行connect: [‘config‘‘public‘‘genesisblock‘‘logger‘‘build‘‘network‘function (cb, scope) {

Next, the following code, loaded with several middleware, tells us that the app accepts ejs template-driven HTML files. View files and pictures, styles and other static files are all in public folders, and this information is definitely more useful than official documents.

277行scope.network.app.engine(‘html‘require(‘ejs‘).renderFile);scope.network.app.use(require(‘express-domain-middleware‘));scope.network.app.set(‘view engine‘‘ejs‘);scope.network.app.set(‘views‘‘public‘‘public‘)));...

Again, the request parameter and response data processing, including the peers blacklist, whitelist filtering, etc., and finally start the service operation:

336行scope.network.server.listen(scope.config.port, scope.config.address, function (err) {

(3) Load logic

Looking at the code, the core logic functions should be: account management, trading, and blockchain. These modules have their order of execution, which we need to introduce separately in a later chapter.

//379Line logic: [' Dblite ',' Bus ',' scheme ',' Genesisblock ',function(CB, SCOPE) {//nested Async.auto Async.auto ({...Account: ["Dblite","Bus","scheme",' Genesisblock ',function(CB, SCOPE)        {New account (scope, CB); }], transaction: ["Dblite","Bus","scheme",' Genesisblock ',"Account",function(CB, SCOPE)        {New Transaction (scope, CB); }], Block: ["Dblite","Bus","scheme",' Genesisblock ',"Account","Transaction",function(CB, SCOPE)        {New Block (scope, CB); }]}, CB);...

(4) Loading module

All of the above code execution results are shared by the modules here. The following code shows that each module uses a consistent (not necessarily the same) parameter and processing method, which is easy to handle:

//411Line modules: [' Network ',' Connect ',' config ',' Logger ',' Bus ',' sequence ',' Dbsequence ',' Balancessequence ',' Dblite ',' Logic ',function(CB, SCOPE) {//For each module use ' domain ' to monitor its error Object.keys (config.modules). ForEach (function(name) {Tasks[name] =function(CB) {var d =require(' domain '). Create (); D.on (' ERROR ',function(ERR) {...}); D.run (function() {...});    }    }); Let each module run Async.Parallel in parallel (tasks,function(Err, results)    {CB (err, results); });

Since the modules here are all parallel processing, it is not necessary to study them.

Summarize

This article begins to drill down into the code, but it's still sketchy. However, the basic architecture of the entire application has been understood. Further research continues, and the direction of the route is clear.

There's a lot of detail in the code, and we didn't do it on a row-by-line basis. Personally, read the code is like reading the article, first of all, the gradual depth, not necessarily the first to read word for word, so inefficient, poor effect.

For this app.js file, it may be a matter of minutes to read it in hand, but it is much more verbose to write it out. If you don't find it easy or even difficult to understand, there may be a lack of commander domain understanding of async components or modules, such as sharing or official documentation.

Link

This series of articles is updated immediately, to keep up to date, please follow the link below

Source Address: Https://github.com/imfly/bitcoin-on-nodejs

ebook reading: http://bitcoin-on-nodejs.ebookchain.org

ebook Download: download page PDF file epub file Mobi file

"Nodejs development Crypto Currency" Seven: app.js Interpretation of Entrance procedure

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.