How to become a better node. JS Developer in 2016

Source: Internet
Author: User
Tags benchmark

This article focuses on some of the best practices and recommendations for node. JS Development, not just for developers, but for those who manage and maintain the node. JS infrastructure. Following these recommendations in this article will allow you to do your daily development work better.

Statement

    • Original address: https://blog.risingstack.com/how-to-become-a-better-node-js-developer-in-2016/
    • Translator: Jingzhung, Web Developer, focuses on JavaScript, node. js, React, Docker, and more.

Using ES2015
In the summer of 2015, ES2015 's final draft (ie, ES6) was officially released. This version adds a lot of new language features to the JavaScript language, mainly including:

    • Arrow functions
    • Template string
    • Rest operator (indeterminate parameter), argument spreading
    • Generator
    • Promises
    • Maps, sets
    • Symbols

and many other features. A more complete list of new features you can learn from Kyle Simpson's ES6 and beyond. And most of these features have been added to node. JS V4.

On the client side, you can also use Babel to take advantage of all the new features of ES6, Babel is a JavaScript translator. Currently on the server side, we are only inclined to use features that are added to the latest stable version, so there is no need to translate the code, which can avoid the potential problems that make us headache.

For more information about ES6 in node. js, you can visit the official site: https://nodejs.org/en/docs/es6/

Callback Convention – supports promise at the same time
In the last year, we might recommend that you expose the error-first callback interface for your module. But with the formal normalization of generator functions and the impending arrival of asynchronous functions, we now suggest that you should expose the error-first callback functions that support promise when writing the interface of the module.

Why do you need this? The first callback interface is to provide backward compatibility, in order to be able to achieve better compatibility in the future, need to provide promise support at the same time.

You can refer to the following example to further understand how the program should be programmed. In this example, the Readpackage function reads the Package.json file and returns its contents through the promise and callback interfaces at the same time.

  Const FS = require (' FS ');    function Readpackage (callback) {//As of now we don't have the    default values in node. js    callback = Callback | | fun  Ction () {}    return new Promise ((resolve, reject) = {      Fs.readfile ('./package.json ', (err, data) = = {        if (ERR) {          reject (err);          Return callback (ERR);        }        Resolve (data);        Return callback (null, data);})}    )    }    Module.exports.readPackage = Readpackage;  

Asynchronous mode
In node. js, for a long time you have only two ways to manage the asynchronous stream: callback or stream. For callback functions,
You can use a library similar to async, with through, BL, Highland and other libraries available for streaming.

However, with the promise, generators, asynchronous functions and so on are gradually introduced into the standard ECMASCRIPT,JS process control has also been greatly improved.

Referring to the development history of asynchronous JavaScript, you can refer to the development of asynchronous JavaScript in this blog post.

Error handling
Error handling plays a critical role in the application development process: Determining when an application crashes, or simply printing error messages, making sure that the application continues to run is difficult.

In order to be able to explain this problem more simply, we decided to divide it into two kinds: Programmer error (programmer errors) and arithmetic error (operational errors).

The programmer error is what we call a bug, because you do not know the exact state of the program running, so you'd better stop running the application immediately (crash the process) when an error occurs.

On the other hand, the operation error is due to problems caused by the system or remote service itself. Example: Request timeout and memory shortage. Based on the characteristics of the error, you can remedy the case and try again, such as file loss, you can go to create the corresponding file.

Error handling in callbacks
If an error occurs during an asynchronous operation, the error object should be passed as the first parameter of the asynchronous function. You must always check the Error object and do error handling.

In the previous example of the callback Convention, we have shown how to prioritize errors in the callback function.

Error handling in Promise
What happens if it is the following code fragment?

  Promise.resolve (() = ' John ')    . Then (() = {      throw new Error (' Ops ');    })    . catch (ex) = {      Console.log (ex);    })    . Then (() = {      throw new Error (' ups ');      Console.log (Doe ');    })  

    • Throws an exception in the 3rd row.
    • The catch handles it and prints in stdout: [Error:ops]
    • Execution continues, and a new error is thrown in the 9th row
    • Without

There's really nothing-the last thrown error will be silent. You need to be aware that you should always use a catch statement as the last link in the Promise chain. This will solve many headache problems for you. Like this:

  Promise.resolve (() = ' John ')    . Then (() = {      throw new Error (' Ops ');    })    . catch (ex) = {      Console.log (ex);    })    . Then (() = {      throw new Error (' ups ');      Console.log (Doe ');    })    . catch (ex) = {      Console.log (ex);    });  

Now the output is as follows:

  [Error:ops]  [Error:ops]  

Use JavaScript standard style
Over the past few years, we have used Jshint, Jscs, eslint and other very useful code quality tools to check our code as automatically as possible.

Recently, when it comes to code style, we use Feross's JavaScript standard style.
The reason for this is that it is very simple: no configuration files are needed, just put them in the project. The main rules include the following:

    • Use 2 spaces as indentation
    • String using single quotation marks – except to avoid escaping
    • Do not include variables that are not used
    • No semicolon
    • Never use (or [start as a line]
    • After keyword, add a space if (condition) {...}
    • function name plus space function name (args) {...}
    • Always use = = = instead of = =, but you can use obj = = NULL to check for null | | Undefined
    • Always handle the Err function parameter of node. js
    • Always add window prefixes for browser global variables, except document and navigator
    • Avoid using global variables such as open, length, Evet, name, and so on, as much as possible.

Of course, if your editor only supports Eslint, here's a Eslint rule library for using the standard style, which is eslint-plugin-standard. After installing this plugin, your. eslintrc file can be the following:

  {      "plugins": [          "Standard"      ],  }  

12-factor Application (the Twelve-factor application)
Today, software is often delivered as a service, called a Web application, or software as a service (SaaS).
The 12-factor Application Manifesto describes best practices for Web application development:

    • Benchmark code: One benchmark code, multiple deployments
    • Dependency: Show claim dependency
    • Configuration: Storing the configuration in the environment
    • Backend services: Treat back-end services as additional resources
    • Build, publish, run: Strictly separate build and run
    • Process: Running an app in one or more stateless processes
    • Port binding: Servicing via port Binding
    • Concurrency: Scaling through the process model
    • Easy handling: Fast Start-up and graceful termination maximizes robustness
    • The development environment is equivalent to the on-line environment: keep development, pre-release, and online environment as much as possible
    • LOG: Log as an event stream
    • Management process: Back-end management tasks run as a one-time process

This theory applies to applications developed by any language and back-end services (database, Message Queuing, caching, etc.).
Start a new project
Always start a new project with the NPM init command. This can create an initial Package.json for your project.

If you want to skip the initial questions and use the default configuration directly, you just need to run NPM Init–yes.

Monitor your App
When a fault or failure is about to occur, timely notify you, can save you the loss.

For application monitoring, you can use similar SaaS products or open source software. In terms of open source software, mainly include: Zabbix, collected, Elasticsearch and Logstash.

If you don't want to deploy on your own, consider using the online service, you can try using trace,
It is the node. js and micro-service monitoring solution developed by our company.

Using the build system
As much as possible to automate everything. There is nothing more boring and irritating than letting development do what should be done by grunt, which is not only a waste of time, but also meaningless. Today Jvavascript's tools are very rich, including Grunt, Gulp, and Webpack, and you know just a few. In Risingstack, most of the front-end development projects are built using Webpack for automation, and other types use gulp for automated tasks. For beginners, Webpack may take a lot of time to understand, so I strongly suggest you read Webpack Cookbook.

Use the latest long-term support (LTS) version of Node
To better obtain stability and new features, we recommend that you use the latest LTS (long-term support) version of node, which is a version with even release numbers. Of course, you can also freely use the latest experimental version, known as the stable release version, using an odd number of release numbers.

If you need to work on multiple projects and use a different version of node. JS, it is recommended that you use a node version manager--NVM.

For more information, you can refer to the posting information on the node. JS Official website:
What are should Know about node. JS V5 and more
Update your project dependencies on a weekly basis
Develop the habit of updating your project dependencies once a week. In this regard, you can use the NPM outdated or the NCU package.

Select the appropriate database
When we talk about node. js and the database, the first technique you might think of is MongoDB. Of course there is nothing wrong with that, but you should not use it directly. Before you do this, you need to ask yourself and your team a few questions. These include the following:

    • Will the application have structured data?
    • Will the application deal with the transaction?
    • How long does the data need to be stored?

Maybe all you need is redis, or if you have structured data, you might want to use Postgrelsql.
If you need to use SQL in node. js, you can look at Knex.

Using semantic versioning (Semantic Versioning)

Reference semantic versioning is a formal convention for the use of three-segment version numbers for compatibility, i.e.: Major.minor.patch, main version, minor version, patch.

Use the major version number if it is an API change that will not be backwards compatible (backward-compatible). Use the minor version number when adding new features and the API changes are backwards compatible. If you are just fixing a bug, you can use the package version number. Fortunately, you can use the Semantic-release module to automate the release of your JavaScript modules.

How to become a better node. JS Developer in 2016

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.