16 years on the Node project, will it be any different? ! Of course, as languages, tools, runtime environments, and development styles change, your Node project will need to keep up to date, so let’s take a look at some of the issues in turn.

  • Now start using ES2015
  • Asynchronous functions support callback conventions and Promise writing
  • Asynchronous mode
  • Error handling
  • Use standard JavaScript code style
  • Twelve catch-22 rules for Web application development
  • Always start a new project with NPM init
  • Always lower case file names
  • Smart.npMRc and correct version management practices
  • Update dependencies in time
  • Choose the appropriate database
  • Monitor your application
  • Using the Build system
  • NPM lifecycle hooks
  • Manage garbage collection
  • Use the long-supported version of Node.js
  • Use semantic version numbers
  • Keep learning and keeping up

Now start using ES2015

Arrow function template string REST parameter, spread operator (spread), function default variable deconstruction assignment generator and Promises Maps, sets and symbols

Most of these new syntax are supported by Node.js V4 (see nodejs.org/en/docs/es6…). It is recommended to use the syntax supported by the new Node interpreter on the server side, or you can use Babel as the compile layer (see the scaffolding for details).

// Deconstruct specific parameters from Express's req.query? Page =2&size=10&word= test let {page, size, word} = req.query;

Asynchronous functions support callback conventions and Promise writing

In the past, when Promise wasn’t a default Node syntax, the recommendation module exported error-first callback as an interface. However, two forms of support are now commonly needed:

const fs = require('fs')

function readPackage(callback=noop) {
  return new Promise((resolve, reject)=>{
    fs.readFile('./package.json', (err, data)=>{
      if(err) {
        reject(err)
        return callback(err)
      }
      resolve(data)
      return callback(null, data)
    })
  })
}

Asynchronous mode

For a long time, there were two ways to manage asynchronous flows in Node: Callback callbacks and Streams can use the async libraries that help us with asynchronous operations and the Through, BL, or Highland libraries, but with the advent of ES6’s generator and promise, Even with the arrival of the await/async keyword built into ES7, things have changed. See the evolution of asynchronous JavaScript for details

Error handling

Sound error handling makes your service more robust. Know when to crash, and then just catch and ignore, or write down the call stack to log and try again, or even restart? We usually need to distinguish between programmer errors and operational errors: The former is restarted directly (in fact, it should be found in the development stage and located online through logger), because the bug written by the programmer will be difficult to deduce the status of the application if not restarted in time, thus more and bigger problems will occur, while the latter is usually not a bug but a case without full consideration. For example, if the external request times out, the external dependent database cannot be connected, or even the disk of the running machine is full, the file to be accessed and written does not exist temporarily. These cases usually require a specific fallback/polyfill in the program. Try to create a new file for a file that doesn’t exist. For a log that always fills up the disk, handle it with a Logstash and logrotate.

Error handling in callbacks

The error-first callback always checks for the presence of the first err at the beginning of the function, and then performs appropriate processing (of course, it can also be passed to the last unified processing of the call stack via next(e))

Error handling in promises

Always include a catch at the end of the promise call chain to handle exceptions

Use standard JavaScript code style

We used to use jsLint, JSHint, and JSCS as our code style checking tools, but as ES6 becomes more popular and new habits develop, we recommend using the ESLint tool along with the ESlint-plugin-standard plugin

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

Twelve catch-22 rules for Web application development

Blood and tears learned from the Rails community, but mostly applicable to our Node project (some practices may be tweaked with the new Docker deployment)

Always start a new project with NPM init

Initialize your Node project using NPM init, and promt to determine your project name, developer information, etc. (you can skip this by using the –yes flag, of course) The main thing you should always do is show the named version of Node Engines (Node-V) to ensure that your development, test, and online environments are using the same version of Node.

{"engines": {"node": "4.2.1"}}

Always lower case file names

Because on OSX and Windows there is no difference between myClass.js and myClass.js, Linux does. So in order for your code to be portable across operating systems (before using require to introduce modules to ensure statements are consistent and unambiguous), always keep lower-case -my-class.js

Smart. NPMRC and correct version management practices

By default, NPM installs new dependent modules, which are not added to package.json by default. At the same time, modules versions are not strictly locked (to ensure that larger versions are consistent). This can cause problems such as not writing dependencies to package.json at release time, missing necessary modules online, and using different modules online. This causes unexplained problems and a lot of depricated warning warnings.

NPM install foobar –save –save-exact or.npmrc so that next time NPM install won’t make a mistake

$ npm config set save=true
$ npm config set save-exact=true
$ cat ~/.npmrc

Of course, if you want more flexible dependency control, npm-shrinkwrap can be generated with the NPM shrinkwrap command to add npm-shrinkwrap.

Update dependencies in time

The above version locks make it easier for you to deal with dependencies, but remember to keep updating dependencies regularly to get updates that fix bugs and optimize performance. You can use NPM Outdated or the NCU toolkit every week

Choose the appropriate database

Most new Noders, when choosing a database, prefer Mongodb. It’s all well and good, but Mongodb isn’t the only option, you should choose it based on your application scenario:

  • Is your data structured
  • Whether your data operations should support transactions
  • Whether your data needs to be persisted

Select a different database: PostgreSQL, Redis, LevelDB, etc

Monitor your application

You need to be aware of the health of your online applications (CPU, Memory, logs, etc.) and need to be notified of any unexpected events. Many open source projects and SaaS products offer comprehensive and powerful monitoring services such as Zabbix, Collectd, ElasticSearch and Logstash. Even combined with Cabot to send messages to wechat public account to remind and so on

Using the Build system

Today’s JavaScript toolchain has a huge choice: Grunt, Gulp, Webpack, etc. On the team, for example, we choose Webpack to assist with front-end development and Gulp to handle a number of other automated tasks (your shell scripts can also be integrated with gulp-shell). Vanilla Build is also recommended (especially if you can do many things with NPM Lifecycle hooks).

NPM lifecycle hooks

Provides nice hooks to make some tasks elegant, and our scaffolding makes a lot of use of this technique

"postinstall": "bower install && grunt build", "postinstall": "if $BUILD_ASSETS; then npm run build-assets; Fi ", "build-assets": "bower install && grunt build" "Scripts /postinstall.sh" (the sh script will automatically access the commands in./node_modules/. Bin because the PATH is added to $PATH)

Manage garbage collection

V8 uses lazy and greedy GC by default. Sometimes waiting for 1.5GB of free memory to reclaim unused memory (so sometimes memory increases are not due to leaks or Node’s usual lazy behavior)

So if you don’t want your Node application to constantly run out of server memory (or if you have to adjust because your machine doesn’t have that much available memory), try using the following command /proc file to start the Node service (recommended in.pm2config, as scaffolding recommends)

web: node --optimize_for_size --max_old_space_size=920 --gc_interval=100 server.js

Use the long-supported version of Node.js

If you need to work on different projects with different Versions of Node, use Node Version Manager (NVM).

Use semantic version numbers

Make sure compatibility is declared with three versions. For formats such as major.minor.patch, different levels of updates require different API updates. Version upgrades can be made more automatic with a Seman-release

Keep learning and keeping up

The active JavaScript and Node.js community is a good thing. New tools and new ideas are added every week, so let’s keep our enthusiasm and technology up (be wary of becoming a copycat, take color and understand the unchanging nature behind each new thing), don’t stay in your own honeypot, do experiments and learn. The following information:

  • Node.js Weekly Newsletter
  • Microservice Weekly Newsletter
  • Changelog Weekly – for Open-Source news

reference

  • How to Become a Better Node.js Developer
  • 10 habits of a happy node hacker 2016
  • Twelve catch-22 rules for Web service development