10 tips to make you a better Node developer in 2017

Source: Internet
Author: User
10 suggestions will be listed below. These suggestions can help you become a better Node developer in 2017. Some of the suggestions I learned in my daily practice, and others learned from those who wrote the most popular Node and npm modules. The following is what we will introduce: I will list 10 suggestions below, which can help you become a better Node developer in 2017. Some of the suggestions I learned in my daily practice, and others learned from those who wrote the most popular Node and npm modules. The following is what we will introduce:

1.Avoid complexity-Try to minimize the size of your code block.

2.Asynchronous programming-Avoid using synchronous code like a plague.

3.Avoid require Blocking-Place all your require statements on the top of the file, because require is synchronous and will block code execution.

4.Understanding require Cache-If you understand it, you can use it; otherwise, it may bring bugs.

5.Always check errors-Errors are not football. Do not throw errors or skip the error check at any time.

6.Only use try… in synchronization code... Catch-In asynchronous code, try... catch does not work. The V8 engine cannot be optimized for try... catch.

7.Return callbacks or use if... Else-A callback is returned to ensure that the execution is not continued.

8.Listen for error events-Almost all Node classes/objects have event emitter (Observer mode) and will broadcast error events to ensure that you have listened to them.

9.Learn about your npm-Use-S or-D to install modules instead of -- save or -- save-dev '.

10.Use the exact version number in package. json: Npm automatically uses the default version number when using-S to install the module. You need to manually modify it to lock the version number. Unless it is an open-source module, do not trust the SemVer (semantic version standard) in your project ).

11. Extra points-use different dependencies. Place the things required by the project in the development stage in devDependencies. Remember to use npm I -- production. The more redundant dependencies, the greater the risk of problems.

Okay. Let's take a look at each of the above points one by one.

Avoid complexity

Let me take a look at the npm creator Isaac Z. some modules written by Schlueter, such as use-strict, are used to force strict mode in Javascript. This module only has three lines of code:

var module = require('module')module.wrapper[0] += '"use strict";'Object.freeze(module.wrap)

So why should we avoid complexity? A famous phrase originated from the US Navy: keep it simple stupid (or "Keep it simple, stupid "). This is the reason. Facts show that the human brain can only maintain five to seven projects in its working memory at any time.

Modularize your code into a smaller part, and you and other developers will better understand it. You can also test it better. Example,

app.use(function(req, res, next) {  if (req.session.admin === true) return next()  else return next(new Error('Not authorized'))}, function(req, res, next) {  req.db = db  next()})

Or

const auth = require('./middleware/auth.js')const db = require('./middleware/db.js')(db)app.use(auth, db)

I believe most people will like the second example, especially simply looking at the name to understand its role. On that day, when you write code, you may think that you know how the code runs. You even want to show how witty you are to connect several functions to the same row. However, you have written a piece of stupid code. If you think about this code in a complicated way, it will be hard to understand it in the future. Ensure that your code is simple, especially in Node asynchronous code.

Of course, there will also be a left-pad event, but in fact it only affects projects dependent on the left-pad module and released a replacement in 11 minutes. The benefits of code minimization exceed its disadvantages. Npm has changed the release policy and any important project should use a cache or private source (as a temporary solution ).

Asynchronous programming

Only a small part of the synchronization code in Node is required. Most of the code is used for command line tools or other scripts unrelated to web applications. Most Node developers write web applications, so using asynchronous code can avoid blocking the scene.

For example, if you are writing a database script or a task that does not need to control parallelism, the following method may be feasible:

let data = fs.readFileSync('./acconts.json')db.collection('accounts').insert(data, (results))=>{  fs.writeFileSync('./accountIDs.json', results, ()=>{process.exit(1)})})

However, when you create a web application, the following statement is better:

app.use('/seed/:name', (req, res) => {  let data = fs.readFile(`./${req.params.name}.json`, ()=>{    db.collection(req.params.name).insert(data, (results))=>{      fs.writeFile(`./${req.params.name}IDs.json`, results, ()={res.status(201).send()})    })  })})

The difference is whether you need to write a system that runs concurrently (usually long-term) or not concurrently (short-term. Based on experience, asynchronous code is always used in Node.

Avoid require Blocking

Node has a simple module loading system that uses the format of CommonJS modules. It is based on the require function. The require function can easily introduce modules in different files. Unlike AMD/requirejs, Node/CommonJS modules are synchronized during loading. The require method is to introduce the content of a module or file export:

`const react = require('react')`

However, most developers do not know that require will be cached. Therefore, as long as the resolved file name (resolved filename) does not change dramatically (for example, if the npm module does not exist ), the module code is only executed and saved to the variable once (in the current process ). This is a good optimization. Of course, even with the cache, you 'd better write your require statement at the beginning. The following code is loaded only when the axios module is used in the route. When a request is sent,/connect slows down because the module needs to be loaded.

app.post('/connect', (req, res) => {  const axios = require('axios')  axios.post('/api/authorize', req.body.auth)    .then((response)=>res.send(response))})

A better way to achieve better performance is to introduce modules before the service is defined, rather than in routing:

const axios = require('axios')const express = require('express')app = express()app.post('/connect', (req, res) => {  axios.post('/api/authorize', req.body.auth)    .then((response)=>res.send(response))})

Know that require will be cached

I mentioned in the previous section that require will be cached, but it is interesting that we also have code outside module. exports. For example:

console.log('I will not be cached and only run once, the first time')module.exports = () => {  console.log('I will be cached and will run every time this module is invoked')}

We learned that some code only runs once. You can use this feature to optimize your code.

Always check errors

Node is not Java. In Java, you can throw an error because if an error occurs, you want the application not to continue execution. In Java, you can use a simple try... catch on the outer layer to handle multiple errors.

But this is not the case in Node. Since Node uses the event loop and asynchronous execution, any errors occur with the error processor (such as try... catch) Context separation, which is useless in Node as follows:

try {  request.get('/accounts', (error, response)=>{    data = JSON.parse(response)  })} catch(error) {  // Will NOT be called  console.error(error)}

However, try... catch can be used in synchronization code. The preceding code snippets can be better reconstructed as follows:

request.get('/accounts', (error, response)=>{  try {    data = JSON.parse(response)  } catch(error) {    // Will be called    console.error(error)  }})

If we cannot wrap the returned content of the request in try... catch, we cannot handle the request errors. Node developers solve this problem by adding an error to the returned parameters. Therefore, we need to manually handle errors in each callback. You can check these errors (judge whether the error is null), and then display the error information to the user or the client and record it, or you can call callback, pass the error parameter to it and send the error back to the upper-level call stack (if you have another callback function on the call stack ).

request.get('/accounts', (error, response)=>{  if (error) return console.error(error)  try {    data = JSON.parse(response)  } catch(error) {    console.error(error)  }})

One trick is that you can use the okay library. You can use it like in the following example to avoid manually checking errors in callback hell (hello, callback hell ).

var ok = require('okay')request.get('/accounts', ok(console.error, (response)=>{  try {    data = JSON.parse(response)  } catch(error) {    console.error(error)  }}))

Return callback or use if... Else

Node is parallel. However, if you are not careful enough, this feature may cause bugs. To ensure security, use return to terminate code execution:

let error = trueif (error) return callback(error)console.log('I will never run - good.')

This prevents execution of some undesirable content (or errors) due to improper code logic processing.

let error = trueif (error) callback(error)console.log('I will run. Not good!')

Make sure to use return to prevent code execution.

Listen for error events

Almost all classes/objects in Node have event distributors (Observer mode) and error events are broadcast. This is a good feature that allows developers to capture these annoying errors before they cause huge consequences.

Develop a good habit of creating an error event listener through. on:

var req = http.request(options, (res) => {  if (('' + res.statusCode).match(/^2\d\d$/)) {    // Success, process response  } else if (('' + res.statusCode).match(/^5\d\d$/))    // Server error, not the same as req error. Req was ok.  }})req.on('error', (error) => {  // Can't even make a request: general error, e.g. ECONNRESET, ECONNREFUSED, HPE_INVALID_VERSION  console.log(error)})

Learn about your npm

Many Node and front-end developers know that when installing a module, saving saves an entry containing the module version information in package. json while installing the module. Of course, there is also -- save-dev which can be used to install devDependencies (modules not required in the production environment ). But do you know whether-S and-D can replace -- save and -- save-dev? The answer is yes.

When installing a module, You need to delete the ^ tag that-S and-D automatically add to the version number of your module. Otherwise, when you use npm install (or npm I) to install the module, the latest image is automatically pulled (the second digit of the version number ). For example, v6.1.0 is an image branch of v6.2.0.

The npm team recommends semver, but you 'd better not. The npm team believes that open-source developers will follow semver, so they automatically add ^ during npm installation. No one can guarantee it, so it is best to lock your version number. A better way is to use shrinkwrap: npm shrinkwrap to generate a file containing a specific version of the dependency.

Related Article

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.