Home IT Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ 2016, the new Node project Precautions     - Do not find ifconfig eth0 and IP address under CentOS6.5 (Linux)

- The several technical presentation Raid under Linux (Linux)

- Linux installed PCRE (Linux)

- Installation salt-minion on RHEL5 (Linux)

- Ubuntu Backup and Recovery (Linux)

- VPS xen openvz kvm (Server)

- The wrong in Linux: too many open files (Linux)

- XP virtual machine under VirtualBox solve occupy 100% CPU problem (Linux)

- Detailed LVM2 (Linux)

- How UTorrent download the ISO image from the command line (Linux)

- E: Sub-process / usr / bin / dpkg returned an error code (1) error solution (Linux)

- Kibana Apache Password Authentication (Server)

- How to make GRub instead of the default Ubuntu software center (Linux)

- Upgrading to MySQL 5.7.9 MySQL 5.6.23 (Database)

- Sqoop data export import command (Database)

- Use read command to read user input (Programming)

- Installing Linux and Windows 10 dual system (Linux)

- Ceph Source Analysis: Network Module (Server)

- Install Open vSwitch under CentOS 6.5 (Linux)

- Linux script commands - terminal recorder (Linux)

 
         
  2016, the new Node project Precautions
     
  Add Date : 2018-11-21      
         
       
         
  Node 2016 development project, what will not the same? ! Of course with the language, tools, operating environment, changing the development mode, your Node project certainly need to keep with the times, then we turn to look at what issues need attention now.

table of Contents

Now started ES2015
Asynchronous callback function supports new writing practices and Promise
Asynchronous mode
Error Handling
Using standard JavaScript code style
Twelve Army Regulation Web application development
Always start a new project with npm init
File name is always lowercase
Intelligent .npmrc management practices and the correct version
Update dependency
Select the appropriate database
Monitor your application
Use the build system
NPM lifecycle hook
Manage garbage collection
The use of long-term support version of Node.js
Using semantic version number
Continuous learning and keep up with trends
Now started ES2015

Arrow Function
Template strings
rest parameter expansion operator (spread), the function defaults
Deconstruction variable assignment
generator and promises
maps, sets and symbols

Most of these new syntax are Node.js V4 support (reference) [https://nodejs.org/en/docs/es6/]
On the server side of the recommended new node supports syntax interpreter, or may be used as compile babel layer (specific reference to the practice of scaffolding)

// Deconstruction specific parameters from the express's req.query? Page = 2 & size = 10 & word = test

let {page, size, word} = req.query;
Asynchronous callback function supports new writing practices and Promise

In the past, when Promise not become the default syntax Node equipped, recommended by the Export module interfaces in the form of error-first callback. But now often need support in two forms:

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

In the past for a long time, the node in general there are two ways to manage asynchronous stream: callback callback and streams flow
The former can help us asynchronous operations async library
The latter can be used through, bl or highland these libraries
But with the arrival of the generator and the promise of es6 even es7 the await / async keyword built soon, the situation has changed. A detailed look at the evolution of asynchronous JavaScript

Error Handling

Sound and reasonable error handling to make your services more robust. You know when to crash, and then only after the catch is ignored, or write down the stack after the call log into the retry, or even need to restart?
We usually need to be treated differently programmer error, operational errors:
The former resumption of direct (in fact found in respect of the development phase, and online through logger positioning), because programmers to write bug, if not lead to the restart state of the application difficult deduction, which occurred more and bigger problems
The latter is usually not a bug, but did not consider the whole case. As external requests overtime, external dependency database Rom, even where the running machine disk full, and write access to a file does not exist temporarily. The case is generally necessary to add a specific fallback / polyfill to deal with in the program. As for the timeout to retry several times for a file that does not exist to try to create a new file, for always filled disk log, and by logstash logrotate to deal with.

Callback Error Handling

error-first convention of callback, always remember that in the beginning of the function to check first if there is a err, then the appropriate treatment (of course, can also be passed to the call stack and finally unified treatment by next (e))

Promise Error handling

Always remember that promise last call chain plus catch to handle exceptions

Using standard JavaScript code style

In the past we use jslint, jshint, jscs as our code style checking tool, but with the popularity of es6, there are some new habits, we recommend using eslint tool, in conjunction with eslint-plugin-standard plug

{
  "Plugins": [
    "Standard"
  ],
}
Twelve Army Regulation Web application development

From the tragic experience of the Rails community, but most also applies to our Node item (Some minor adjustments in practice there may be deployed under the new docker)

A reference code is Codebase, multiple deployment deploy
Shows the declaration and isolation dependence
In the configuration on the environment
An external back-end services as additional resources
Strict separation of construction and operating environment
One or more stateless processes running applications
To provide services through the port binding (Port binding)
Be extended by the process model
Fast Start and elegant termination to maximize robustness
As much as possible to keep the development, pre-release, the same online environment
The log as an event stream
Manage tasks run as a one-time process
Always start a new project with npm init

By npm init to initialize your project node, determine the name of your project, developer information by promt (Of course, you can skip through --yes flag)
Tip: You should always display the main name of your node engines version (node -v), make sure that your development environment, test environment and the online environment is to use the same version of the node.

{
    "Engines": {
        "Node": "4.2.1"
    }
}
File name is always lowercase

Because OSX and Windows systems, MyClass.js and myclass.js no difference, Linux is distinguished. So you write code for different operating systems are portable (in use require to introduce module ensures consistent statement is clear), so always keep lowercase - my-class.js

Intelligent .npmrc management practices and the correct version

Default, npm installing a new dependent modules, default will not be added to the package.json. At the same time, modules of the version number is not strictly lockup (^ sharp major version number to ensure consistency) this will cause some problems, such as when to rely on published found no written to package.json, resulting in a lack of online necessary modules, online found not deploy the same modules used, resulting in a large number of problems and inexplicable depricated warning warning.

So install the new depends recommends such wording: npm install foobar --save --save-exact
Or write .npmrc so next npm install will not mistake it

$ Npm config set save = true
$ Npm config set save-exact = true
$ Cat ~ / .npmrc
Of course, if you rely on if you want a more flexible control can generate npm-shrinkwrap.json added to the repository through npm shrinkwrap command, so the build environment to build but also to ensure a unified version.

Update dependency

The above version let you lock face dependent modules when more calm, but remember to keep regularly updated dependence, thereby obtaining bug fixes and performance optimization functional updates. You can use npm outdated weekly or ncu Kit

Select the appropriate database

Most new noder, in the choice of database, prefer Mongodb. It is indeed very good, but not the only option Mongodb,
You should based on your application scenario to choose:

Your data is structured
Do you want to support transaction data manipulation
Do you need data persistence
Thereby selecting different databases: such as PostgreSQL, Redis, LevelDB etc.

Monitor your application

You want to run your online health applications well known (CPU, Memory, logs, etc.), some emergency situations requires timely notification.
Many open source projects and SaaS products provide powerful sound monitoring service, such as Zabbix, Collectd, ElasticSearch and Logstash. Even combine the micro-channel public number to Cabot message reminders, and more

Use the build system

JavaScript tool chain now has plenty of choice: Grunt, Gulp, Webpack like. For example, in the team, we have chosen Webpack to assist front-end development, gulp a lot to handle other automation tasks (your shell script can also gulp-shell integrated come). Of course, we also recommend using vanilla build (especially if you can combine npm lifecycle hooks do a lot of things)

NPM lifecycle hook

Provides a good hook to achieve the task makes some very elegant, our scaffolding extensive use of such techniques

"Postinstall": "bower install && grunt build",

"Postinstall": "if $ BUILD_ASSETS; then npm run build-assets; fi",
"Build-assets": "bower install && grunt build"

# If the script becomes complicated can separate files:
"Postinstall": "scripts / postinstall.sh" (sh script will automatically have access to ./node_modules/.bin commands, because the path is added to the $ PATH)
Manage garbage collection

v8 default lazy and greedy GC. Sometimes until 1.5GB free before going to reclaim unused memory (memory so sometimes up not because of leaking or node's usual lazy behavior)

So you do not want to own node application server is often the memory is full (or you have to adjust, because the available memory on your machine, not so much), try using the following command / proc file to start the service node (recommended in writing. pm2config, just as scaffolding recommended)

web: node --optimize_for_size --max_old_space_size = 920 --gc_interval = 100 server.js
The use of long-term support version of Node.js

If you need to work on different projects, and projects with different node version is not the same, you can use the node version manager (nvm)

Using semantic version number

Through three sections to ensure that the version number of good compatibility statement. Such a format major.minor.patch, different levels of upgrade API update requirements are not the same. You can make semantic-release version upgrades by more automated

Continuous learning and keep up with trends

JavaScript and Node.js community very active, indeed a good thing. Every week new tools added to new ideas, so that we always maintain the enthusiasm and technological upgrading (vigilance himself into a dog suit, to take the essence of color and learn new things each behind the same), do not stay own honeypots, to DIY test and learning.
     
         
       
         
  More:      
 
- Add a custom encryption algorithm in OpenSSL (Linux)
- Python-- for anomalies and reflection of objects articles (Programming)
- Error code: 2013 Lost connection to MySQL server during query (Database)
- Python Django model within the class meta Detailed (Programming)
- MySQL EXPLAIN SQL output description (Database)
- C ++ 11 feature: auto keyword (Programming)
- Matters Oracle 11.2 single instance when connecting ASM need to pay attention and deal with the problem (Database)
- Linux server network penetration testing (Linux)
- Linux Services Comments (Linux)
- C ++ Supplements - malloc free and new delete the same and different (Programming)
- Use exp exported EXP-00091 error (Database)
- Common DDOS attacks (Linux)
- Lucene Getting Started Tutorial (Server)
- Java implementation heap sort (large root heap) (Programming)
- Reason C ++ program running under Linux a segmentation fault core dumped in (Programming)
- To compile and install OpenCV-2.3.1 FFmpeg-2.1.2 under CentOS (Linux)
- GDB remote connections RX Probe online debug program (Programming)
- Java implementation linear table - represents the order of representation and chain (Programming)
- Under Ubuntu 15.04 installation JDK8 (Linux)
- Installation through the network Debian 7 (Wheezy) (Linux)
     
           
     
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.