From NPM tips to express plug-in mechanism design

Source: Internet
Author: User

Most of the time, we only use NPM install,init,publish and other functions, but it is very good design, there are many we do not understand

Look at it together.

Global command

Using Nodejs to write CLI tools is very cool, I've done a lot of this.

    • KP = kill by port
    • JE = JSON editor
    • MH = start MONGO here

The core is the configuration in the Package.json.

"preferGlobal": "true","bin": {  "mh": "index.js"},

Can

The principle is simple, it is to throw these commands into the environment variable, equal to

mh = node /npm_install_path/index.js

If I'm not mistaken, it's a soft-connect implementation.

ln -s  /npm_install_path/index.js /bin/mh
NPM Link

Why do you know the principle of it? Because every time the CLI is written to the NPMJS, and then installed, and then the test is correct, too cumbersome, if the use of testing, path, etc. is also more troublesome

Later found

npm link

will put the development code directly on the local completion of the above things, cool dead

Link, there will be a hint

/USERS/SANG/.NVM/V0.10.38/BIN/NMM-/users/sang/.nvm/v0.10.38/lib/node_modules/nmm/index.js
/USERS/SANG/.NVM/V0.10.38/LIB/NODE_MODULES/NMM-/USERS/SANG/WORKSPACE/MOA/NMM

How can I confirm that it is a soft connection?

?  nmm git:(master) ls -alt /Users/sang/.nvm/v0.10.38/bin/nmmlrwxr-xr-x  1 sang  staff  32 Jul  7 15:38 /Users/sang/.nvm/v0.10.38/bin/nmm -> ../lib/node_modules/nmm/index.js
The Common Start,test

Generally I like to rewrite the start and test commands, such as

"scripts": {  "start": "nodemon ./bin/www",  "test": "mocha -u bdd"},

npm startstart the Express service by using Nodemon.

Pass npm test to run Mocha test.

Both semantics and convenience are good.

More See Https://docs.npmjs.com/cli/start

NPM Run

However, the NPM Support command is that much, probably not enough, for example, I want to test code coverage

"scripts": {  "start": "npm publish .",  "test": "./node_modules/.bin/gulp",  "mocha": "./node_modules/.bin/mocha -u bdd",  "cov":"./node_modules/.bin/istanbul cover ./node_modules/mocha/bin/_mocha --report lcovonly -- -R spec && cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js && rm -rf ./coverage"},

Obviously there is no npm cov order, then how to do? Don't worry, you can npm run-script fix it.

Above the scripts definition, you can do this

npm run cov

For a custom script, this solves the problem, and its implementation is simple, but very practical.

Pre-commit

Sometimes we have the need to do a test before submitting the code, if

npm test && git push

It's too much trouble, and programmers should be a little bit lazy.

Is there a simpler way? Pre-commit

npm install --save-dev pre-commit

Usage is to add pre-commit a field to an array in Package.json

{  "name": "437464d0899504fb6b7b",  "version": "0.0.0",  "description": "ERROR: No README.md file found!",  "main": "index.js",  "scripts": {    "test": "echo \"Error: I SHOULD FAIL LOLOLOLOLOL \" && exit 1",    "foo": "echo \"fooo\" && exit 0",    "bar": "echo \"bar\" && exit 0"  },  "pre-commit": [    "foo",    "bar",    "test"  ]}

As defined above git push , the Foo,bar and test are executed sequentially, which is equivalent to

NPM run foo
NPM Run Bar
NPM Test
git push

Install

Our most commonly used NPM install is installing the file in the node module into Node_modules, which is a good understanding, so what if I want to customize the installation?

As we said above Https://github.com/observing/pre-commit, it is necessary to install the Pre-commit script first, this time what to do?

We can actually customize the install command in the scripts

"install": "node install.js",

At npm install pre-commit the time, it will download the code, and then he will execute the contents of the install script. That is, in the install.js, it can do the things you want to do, scripts, compile C extensions, are very simple

Another discussion on install

We generally write the module when, first of all npm init , and then add a lot of code, such as you want to add test, you may also have examples, and even put a lot of doc, these things, do you have this npm people download it?

It's a horrible thing to think about.

NPM solutions and Git scenarios, Git is created .gitignore , and NPM does the same

touch .npmignore

And then put on the inside want to filter, do not want users to install time to download the good

The more annoying is that Https://github.com/github/gitignore actually didn't

Circular references

Circular references are very common in iOS development, that is, referencing each other, resulting in the inability to reference the count to zero, can not clean up the memory, and then pull away

See NPM, for example a module relies on B module,

{  "name": "A"  "version": "0.1.2",  "dependencies": {    "B": "0.1.2"  }}

When you are finished installing

├── node_modules│   └── B├── package.json└── README.md

What if both A and B depend on C?

After installation

├── node_modules│   ├── B│   │   ├── node_modules│   │   └── package.json│   └── C   ├── package.json└── README.md

So that B can quote c,c, it doesn't have to be installed.

The problem is Node_modules/b/package.json.

{  "name": "B"  "version": "0.1.2",  "dependencies": {    "C": "0.0.1"  },  "scripts": {    "postinstall": "node ./node_modules/C make"  }}

After installing B, the installation of C is not performed, mainly path variables, it is simple, the path can be judged

// node_modules/B/runMe.jsvar deps = [‘C‘], index = 0;(function doWeHaveAllDeps() {  if(index === deps.length) {    var C = require(‘C‘);    C.make();    return;  } else if(isModuleExists(deps[index])) {    index += 1;    doWeHaveAllDeps();  } else {    setTimeout(doWeHaveAllDeps, 500);  }})();function isModuleExists( name ) {  try { return !!require.resolve(name); }  catch(e) { return false }}

If you want to try, refer to Http://krasimirtsonev.com/blog/article/Fun-playing-with-npm-dependencies-and-postinstall-script

This problem is not common, less, but it postinstall does let the brain hole open a thing

Postinstall

If you are familiar with mongoose hooks, you will know what the pre and post mean, in general, the pre is Previos meaning, post is the meaning after.

Then Postinstall literally, that is, the callback to be executed after installation.

Take a look at the document

Https://docs.npmjs.com/misc/scripts

It's really a post-installation callback, which means we can do more with NPM.

Let's take a look at NPM and provide those callbacks.

    • Prepublish:run before the package is published. (Also run on local npm install without any arguments.)
    • Publish, Postpublish:run after the package is published.
    • Preinstall:run before the package is installed
    • install, Postinstall:run after the installed.
    • Preuninstall, Uninstall:run before the package is uninstalled.
    • Postuninstall:run After the package is uninstalled.
    • preversion, Version:run before bump the package version.
    • Postversion:run After bump the package version.
    • pretest, test, posttest:run by the NPM Test command.
    • prestop, Stop, poststop:run by the NPM Stop command.
    • Prestart, start, poststart:run by the NPM Start command.
    • Prerestart, restart, postrestart:run by the NPM restart command. NOTE:NPM Restart would run the stop and start scripts if no restart script is provided.

Rub, too good, the goods are really too full, then let's see how to use the NPM callback to do bad things

Express plug-in mechanism design

We all know that Express is based on connect, with the concept of middleware middleware, which itself follows a small but beautiful design philosophy, leading to its very streamlined

From [email protected], it can only do a little bit of things, if you want to design a complex large system, it is inevitable and code structure, modules, components and other combat

From my point of view, these things can be understood as a business plug-in, for example, for a framework, user management should be like Ruby in the form of devise, as a gem, if the code refers to the call is good.

Gem + Rails plugin mechanism can be done, then Express + NPM is also possible, but we lack of plugin mechanism, this article first not talk about plugin mechanism, first of all, the use of NPM callback to achieve its possibility

For example, in a boilerplate project, we install plugins

npm install --save moa-plugin-user

After the installation is complete, we need to make a plugin registration for the files or configuration in the project, can these things be put into postinstall?

All that is left is the Nodejs code, and everyone writes it.

How to learn

https://docs.npmjs.com/

The document is good, but it is not easy to understand Ah, and sometimes used to see

For development, the code in hand, the world I have, especially the Nodejs module is completely open, you do not see it all in your project directory, naked.

Outside of the code, look at the Node_modules directory, open Package.json look, if you find that you do not understand to check the document, so the effect is the best.

Look at the module can pick some better, open source more than the contribution of the module

Learn from other people's code, this should be the strongest learning ability, is long-term, with you to encourage.

End of full text

Welcome to my public number "node full stack"

From NPM tips to express plug-in mechanism design

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.