10 tips for programmers using node

Source: Internet
Author: User
Tags npm scripts

For nearly 20 years now, JavaScript has lacked other attractive programming languages such as Python and Ruby: command-line interface, REPL, Package Manager, and well-organized open source community. Thanks to node. js and NPM, today's JavaScript niaoqianghuanpao. Web developers have powerful new tools, and the next step is to see their imaginations.

Here's a list of tips and tricks to keep you happy with your node program.

1. Start a new project with NPM Init

NPM has an init command that will guide you through the process of creating a Package.json file. Even if you are very familiar with Package.json and its properties, you can use NPM init as an easy way to get your new program or module on track. It can intelligently set default values for you, such as inferring the module name from the name of the upper directory, reading the creator's information from the ~/.NPMRC, and using your Git settings to determine the code base.

mkdir MY-NODE-APPCD MY-NODE-APPNPM Init
2. Declaring all dependencies

It's a good practice to stick with--save (or--save-dev) when installing a module locally on a project. These options add the specified module to the Package.json dependencies (or devdependencies) manifest and use a reasonable default semver range.

NPM Install Domready--save

Note that NPM now uses the Semver range of the caret style:

"Dependencies": {  "Domready": "^1.0.4"}
3. Specify the startup script

By setting the Scripts.start in Package.json, you can start the program with NPM start on the command line. This is handy because other node developers who have cloned your program can easily run it without guessing.

Bonus: If you define Scripts.start in Package.json, you don't need to Procfile (Heroku platform uses procfile to declare what commands to run on your program's Dynos). Using NPM start automatically creates a procfile as a web process.

Here is an example of a startup script:

"Scripts": {  "start": "Node Index.js"}
4. Specifying a test script

Just as everyone on the team should be able to run the program, they should also be able to test it. The scripts.test in Package.json is used to specify the script that runs the test suite. If you run the test with something like Mocha, be sure to include it in the devdependencies in Package.json and point to the file installed locally on your project instead of the mocha of the global installation:

"Scripts": {  "test": "Mocha"}
5. Do not put dependencies in the source version control

Many of the NPM modules used by node programs have C-written dependencies, such as Bson, WS, and Hiredis, which must be compiled under Heroku's 64-bit Linux architecture. The compilation process can be time-consuming. To make the build process as fast as possible, Heroku node Buildpack caches the dependencies after they are downloaded and compiled for reuse in subsequent deployments. This cache is designed to reduce network traffic and reduce compilation times.

Ignoring the Node_modules directory is also the NPM practice recommended by the module creator. There is one less difference between the application and the module!

echo Node_modules >> Gitignore
6. Configure NPM with environment variables

The following is excerpted from the NPM configuration:

All environment variables beginning with npm_config_ will be interpreted as configuration parameters. For example, when there is npm_config_foo=bar in the environment, the configuration parameter foo is set to bar. Any environment configuration that does not give a value is set to true. Configuration values are not case sensitive, so Npm_config_foo=bar is the same.

Recently, there are procedural environments in all Heroku constructs. This change allows node users on Heroku to control their NPM configuration without having to modify the program code. The habit of # # is a perfect example of this approach.

7. Take your own NPM registration center

The public NPM Registry has seen rapid growth in recent years and is therefore occasionally unstable. So many node users are looking for alternatives outside the public registry, either for speed and stability in the development and build process, or because they want to place a private node module.

Some of the NPM registries that have been available for selection have emerged in the last few months. Nodejitsu and Gemfury provide a private registry for fees, and there are also some free, such as Mozilla's read-only s3/cloudfront mirrors and Maciej Ma?ecki's European mirrors.

It is easy to configure the node program to use the custom registry on Heroku:

Heroku Config:set npm_config_registry=http://registry.npmjs.eu
8. Track expired dependencies

If you have been programming long enough, you may have already experienced the worst of dependency hell. Fortunately, node. js and NPM have embraced Semver, the semantic version management specification, setting a robust dependency management precedent. In this scenario, the version number and the way they are changed convey meaning to the underlying code, and what is modified from one version to the next.

NPM has a command that few people know, outdated. It can be used in conjunction with NPM Update, to find out that the dependencies of the program have expired and need to be updated:

CD MY-NODE-APPNPM outdatedpackage            current  wanted     Latest location  -------            -------  ------     ------  --------Express              3.4.8   3.4.8  4.0.0-rc2  expressjade                 1.1.5   1.1.5      1.3.0  jadecors                 2.1.1   2.1.1      2.2.0  corsjade                0.26.3  0.26.3      1.3.0  Mocha > Jadediff                 1.0.7   1.0.7      1.0.8  Mocha > Diffglob                 3.2.3   3.2.3      3.2.9  Mocha > Globcommander            2.0.0   2.0.0      2.1.0  Mocha > Commander

If you're doing an open-source node program or module, take a look at David-dm,nodeico and Shields.io, and you can use the image badges provided by these three excellent services to display vivid dependency information on the project's Readme or website.

9. Run a custom build step with NPM scripts

As the NPM ecosystem continues to grow, the automation options for development and build processes will grow with it. Grunt is by far the most popular build tool in node world, but new tools like Gulp.js, as well as ordinary old-fashioned NPM scripts, are also popular because of the lighter load.

When you deploy the node program to Heroku, run the NPM install--production command to ensure that the program's NPM dependencies are downloaded and loaded. But that command will do something else: it will run all of the NPM script hooks you define in the Package.json file, such as preinstall and Postinstall. Here's a sample:

{  "name": "My-node-app",  "version": "1.2.3",  "scripts": {    "preinstall": "Echo here it comes!",    " Postinstall ":" Echo There it goes! ",    " Start ":" Node Index.js ",    " test ":" Tap Test/*.js "  }

These scripts can be in-line bash commands, or they can point to executable command-line files. You can also reference other NPM scripts within the script:

{"  scripts": {    "postinstall": "NPM Run build && npm run Rejoice",    "Build": "Grunt",    "rejoice" : "Echo yay!",    "Start": "Node Index.js"  }}
10. Try something new

ES6, the next version of the ECMAScript language specification, known as JavaScript by Volkswagen, has a job name of harmony. Harmony brings a lot of exciting new features to JavaScript, many of which are already in the newer version of node.

Harmony implements a number of new features, such as block scopes, generators, proxies, weak mappings, and so on.

To enable the Harmony feature in your node program, you need to specify a newer node engine, such as 0.11.x, and set the--harmony option in the startup script:

{"  scripts": {    "start": "Node--harmony index.js"  },  "engines": {    "node": "0.11.x"}  }
Browserify.

Client-side JavaScript has a messy such as-like legacy code, but that's not the language's fault. Due to the lack of a reasonable dependency management tool, the jquery-plugin copy-The Dark Age of pasting has lasted for many years. Thanks to NPM, take us to the front-end of the revitalization of the era: the NPM registry as Wild Weeds, the module designed for the browser has shown an astonishing growth momentum.

Browserify is a magical tool that allows the node module to be used in a browser. If you're a front-end developer, Browserify will change your life. It may not be today, nor tomorrow, but not too long. If you want to start using browserify, see these articles.

10 tips for programmers using node

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.