"Introduction to Node.js" Trial Reading: 2.6 Packages and NPM

 

Node organizes its own core modules, and also enables third-party file modules to be written and used in an orderly manner. But in third-party modules, the modules are still hashed in various places and cannot be directly referenced to each other. Outside of modules, packages and NPM are a mechanism for linking modules together. Before introducing NPM, the package specification of CommonJS has to be mentioned. JavaScript does not have a module and package structure like Java or other languages. Node's implementation of the module specification solves the problem of code organization such as variable dependencies and dependencies to a certain extent. The emergence of packages is to further organize JavaScript code on the basis of modules. Figure 2-9 is a schematic diagram of the package organization module. Figure 2-9 Schematic diagram of package organization module The definition of CommonJS package specification is actually very simple. It consists of package structure and package description file. The former is used to organize various files in the package, and the latter is used to describe the package. relevant information for external read analysis. 2.6.1 Package Structure A package is actually an archive file, that is, a directory is directly packaged as a file in .zip or tar.gz format. After installation, it is decompressed and restored to a directory. A package directory that is fully compliant with the CommonJS specification should contain the following files. package.json: Package description file. bin: The directory used to store executable binaries. lib: Directory for storing JavaScript code. doc: Directory for storing documentation. test: code used to store unit test cases. It can be seen that the CommonJS package specification has been considered from the aspects of documentation, testing, etc. When a package is finished and released to the public, users will have a solid feeling when they see the unit tests and documentation. 2.6.2 Package description file and NPM The package description file is used to express non-code-related information. It is a file in JSON format - package.json, located in the root directory of the package, and is an important part of the package. And all the behavior of NPM is closely related to the fields of the package description file. Since the CommonJS package specification is still in the draft stage, NPM has made certain trade-offs in practice. The specific details will be introduced later. CommonJS defines some required fields for the package.json file as follows. name. Package names. The specification defines that it needs to consist of lowercase letters and numbers, and can contain . , _ and -, but spaces are not allowed. The package name must be unique to avoid misunderstanding of duplicate name conflicts when publishing to the outside world. In addition to this, NPM also recommends not to include node or js in the package name to repeatedly identify it as a JavaScript or Node module. description. Introduction to the package. version. version number. a semantic version number, which is http://semver.org/ has a detailed definition, usually in major.minor.revision format. This version number is very important and is often used in some version control situations. keywords. Keyword array, which is mainly used for classification search in NPM. A good keyword array helps users quickly find your package. maintainers. List of package maintainers. Each maintainer consists of three attributes: name, email, and web. Example: "maintainers": [{ "name": "Jackson Tian", "email": "[email protected]", "web": " http://html5ify.com " }] NPM uses this property to Authorization authentication. contributors. List of contributors. In the open source community, it is a common thing to provide code for open source projects. If the name can appear in the contributors list of well-known projects, it is a more honorable thing. The first contribution in the list should be the author of the package himself. It has the same format as the maintainer list. bugs. A web address or email address where bugs can be reported. licenses. List of licenses used by the current package, indicating under which licenses this package can be used. It has the following format: "licenses": [{ "type": "GPLv2", "url": " http://www.example.com/licenses/gpl.html Schlueter is created separately and provides Node package manager for Node services, which needs to be installed separately. Later, in v0.6.3, it was integrated into Node as the default package manager and installed as part of the package. Later, Isaac Z. Schlueter also became the head of Node. In the specification of the package description file, the fields actually required by NPM mainly include name, version, description, keywords, repositories, author, bin, main, scripts, engines, dependencies, and devDependencies. The difference from the package specification is that there are four more fields of author, bin, main and devDependencies, which are explained below. author. package author. bin. Some package authors want the package to be available as a command line tool. After the bin field is configured, the script can be added to the execution path through the npm install package_name -g command, which can then be executed directly on the command line. This is how the previous node-gyp was installed. A module package installed via the -g command is called global mode. main. The module import method require() will first check this field when importing a package, and use it as the entry for other modules in the package. If this field does not exist, the require() method will look for the index.js, index.node, and index.json files in the package directory as the default entry. devDependencies. Some modules require dependencies only during development. Configuring this property can prompt subsequent developers of the package to install the dependent package. The following is the package.json file of the well-known framework express project, which has certain reference significance: { "name": "express", "description": "Sinatra inspired web development framework", "version": "3.3.4", " author": " "scripts": { "prepublish": "npm prune", "test": "make test" }, "engines": { "node": "*" }} 2.6.3 NPM common functions CommonJS package specification is theory, NPM is one of those practices. NPM is to Node what gem is to Ruby, and pear is to PHP. For Node, NPM helps complete the release, installation and dependencies of third-party modules. With NPM, a good ecosystem is formed between Node and third-party modules. With NPM, users can quickly install and manage dependencies. In addition, NPM has some clever uses, which we will introduce in detail below. 1. View help After installing Node, execute the npm –v command to view the current NPM version: $ npm -v1.2.32 Before you are not familiar with NPM commands, you can directly execute NPM to view the help guide instructions: $ npmUsage: npm < command>where <command> is one of: add-user, adduser, apihelp, author, bin, bugs, c, cache, completion, config, ddp, dedupe, deprecate, docs, edit, explore, faq, find, find- dupes, get, help, help-search, home, i, info, init, install, isntall, issues, la, link, list, ll, ln, login, ls, outdated, owner, pack, prefix, prune, publish, r, rb, rebuild, remove, restart, rm, root, run-script, s, se, search, set, show, shrinkwrap, star, stars, start, stop, submodule, tag, test, tst, un, uninstall, unlink, unpublish, unstar, up, update, version, view, whoaminpm <cmd> -h quick help on <cmd>npm -l display full usage infonpm faq commonly asked questionsnpm help <term> search for help on <term>npm help npm involved overviewSpecify configs in the ini-formatted file: /Users/ jacksontian/.npmrcor on the command line via: npm <command> --key valueConfig info can be viewed via: npm help [email protected] /usr/local/lib/node_modules/npm can be seen, listed in the help For all commands, npm help <command> can view specific command descriptions. 2. Installing dependent packages is the most common usage of NPM, and its execution statement is npm install express. After executing this command, NPM will create the node_modules directory in the current directory, then create the express directory in the node_modules directory, and then extract the package to this directory. After installing the dependencies, call require('express') directly in the code; The package can be imported. The require() method will find the location of express through the module path when doing path analysis. The two steps of module introduction and package installation are complementary. Global mode installation If the package contains command line tools, then you need to execute the npm install express -g command to install in global mode. It should be noted that global mode does not mean that a module package is installed as a global package, it does not mean that it can be referenced by require() from anywhere. The term global mode is actually inaccurate and misleading. Actually, -g is to install a package as a globally available executable command. It links the actual script to the same path as the Node executable according to the bin field configuration in the package description file: "bin": { "express": "./bin/express"}, in fact, via glob mode All installed module packages are installed into a unified directory, which can be calculated as follows: path.resolve(process.execPath, '..', '..', 'lib', 'node_modules' ); if the Node executable's location is /usr/local/bin/node, then the modules directory is /usr/local/lib/node_modules. Finally, the executable file configured in the bin field is linked to the executable directory of Node through a soft link. Install from local For some packages that are not published to NPM, or packages that cannot be installed directly due to network reasons, you can download the package to the local and then install it locally. For local installations, simply specify the location of the package.json file for NPM: it can be an archive file containing package.json, a URL, or the location of a directory with a package.json file in it . The specific parameters are as follows: npm install <tarball file>npm install <tarball url>npm install < folder>Install from unofficial sources If you cannot install from official sources, you can install from mirror sources. When executing the command, add --registry= http://registry.url is enough , the example is as follows: npm install underscore --registry= http://registry.url If the mirror source installation is almost used in the process of use, you can execute the following command to specify the default source: npm config set registry http://registry.url 3. NPM hook command Another thing to note is that C/C++ modules are actually compiled before they can be used. The proposal of the scripts field in package.json is to allow the package to provide a hook mechanism during installation or uninstallation. Examples are as follows: "scripts": { "preinstall": "preinstall.js", "install": "install.js", "uninstall": "uninstall.js", "test": "test.js"} When executing npm install <package> in the above fields, the script pointed to by preinstall will be loaded and executed, and then the script pointed to by install will be executed . When executing npm uninstall <package>, the script pointed to by uninstall may do some cleanup etc. When npm test is executed in a specific package directory, the script pointed to by test will be run. An excellent package should contain test cases, and configure the command to run the test in the package.json file, so that users can run the test cases to check whether the package is stable and reliable. 4. Publishing the package In order to connect the entire NPM process, here will demonstrate how to write a package, publish it to the NPM repository, and install it back locally through NPM. We try to keep the content of the module module as simple as possible. Here we use sayHello as an example. The relevant code is as follows: exports.sayHello = function () { return 'Hello, world.';}; Save this code as hello.js . Although the content of the initial package description file package.json file is relatively large, it does not need to be written line by line when actually publishing a package. The npm init command provided by NPM will help you generate the package. no test specified\" && exit 1" }, "repository": "", "keywords": [ "Hello", "world" ], "author": "Jackson Tian", "license": "MIT"}Is this ok? (yes) yesnpm WARN package.json [email protected] No README.md file found! NPM fills in the options one by one through question-based interaction, and finally generates a preview package description file. If you are satisfied, enter yes and you will get the package.json file in the directory. Registering a Package Repository Account In order to maintain packages, NPM must use a repository account to allow publishing packages to the repository. The command to register an account is npm adduser. This is also a question-based interactive process, which can be done in order: $ npm adduserUsername: (jacksontian)Email: ([email protected]) Upload package The command to upload the package is npm publish <folder>. In the directory where the package.json file you just created is located, execute npm publish. Start uploading the package. The relevant code is as follows: $ npm publish .npm http PUT no test specified\" && exit 1" }, "repository": "", "keywords": [ "Hello", "world" ], "author": "Jackson Tian", "license": "MIT"}Is this ok? (yes) yesnpm WARN package.json [email protected] No README.md file found! NPM fills in the options one by one through question-based interaction, and finally generates a preview package description file. If you are satisfied, enter yes and you will get the package.json file in the directory. Registering a Package Repository Account In order to maintain packages, NPM must use a repository account to allow publishing packages to the repository. The command to register an account is npm adduser. This is also a question-based interactive process, which can be done in order: $ npm adduserUsername: (jacksontian)Email: ([email protected]) Upload package The command to upload the package is npm publish <folder>. In the directory where the package.json file you just created is located, execute npm publish. Start uploading the package. The relevant code is as follows: $ npm publish .npm http PUT folder>. In the directory where the package.json file you just created is located, execute npm publish. Start uploading the package. The relevant code is as follows: $ npm publish .npm http PUT folder>. In the directory where the package.json file you just created is located, execute npm publish. Start uploading the package. The relevant code is as follows: $ npm publish .npm http PUT http://registry.npmjs.org/hello_test_jackson npm http 201 http://registry.npmjs.org/hello_test_jackson npm http GET http://registry.npmjs.org/hello_test_jackson npm http 200 http://registry.npmjs.org/hello_test_jackson npm http PUT http://registry.npmjs.org/hello_test_jackson/0.0.1/-tag/latest npm http 201 http://registry.npmjs.org/hello_test_jackson/0.0.1/-tag/latest npm http GET http://registry.npmjs.org/hello_test_jackson npm http 200 http://registry.npmjs.org/hello_test_jackson npm http PUT http://registry.npmjs.org/hello_test_jackson/-/hello_test_jackson-0.0.1.tgz/-rev/2-2d64e0946b86687 8bb252f182070c1d5npm http 201 http://registry.npmjs.org/hello_test_jackson/-/hello_test_jackson-0.0.1 .tgz/-rev/2-2d64e0946b86687 8bb252f182070c1d5+ [email protected] During this process, NPM will package the directory into an archive and upload it to the official source repository. Install the package In order to experience and test the package uploaded by yourself, you can change the directory to execute npm install hello_test_jackson to install it: $ npm install hello_test_jackson --registry= http://registry.npmjs.org npm http GET http://registry.npmjs. org/hello_test_jackson npm http 200 http://registry.npmjs.org/hello_test_jackson [email protected] ./node_modules/hello_test_jackson manage package permissions Usually, only one person has permission to publish a package. If you need multiple people to publish, you can use the npm owner command to help you manage package owners: $ npm owner ls eventproxynpm http GET https://registry.npmjs.org/eventproxy npm http 200 https://registry.npmjs.org /eventproxy jacksontian <[email protected]> With this command, you can also add a package owner, delete a package owner: npm owner ls <package name>npm owner add <user> <package name>npm owner rm <user> <package name>5. Analyze the package During the process of using NPM, you may not be able to confirm whether the desired package can be successfully imported through require() in the current directory. At this time, you can execute npm ls to analyze the package. This command can analyze all the packages in the current path that can be found through the module path, and generate a dependency tree, as follows: $ npm ls/Users/jacksontian├─┬ [email protected]│ ├── [email protected] │ ├── [email protected]│ ├── [email protected]│ ├── [email protected]│ └── [email protected]├── [email protected]└── [email protected] .32.6. 4 Local NPM There is a certain difference between the use of NPM in the internal application of the enterprise and the use of the open source community. The limitation of enterprises lies in that, on the one hand, they need to enjoy the benefits of low coupling and project organization brought by module development, and on the other hand, they need to consider the issue of module confidentiality. So, sharing and publishing via NPM is potentially risky. In order to enjoy the numerous packages on NPM at the same time, and at the same time to keep secrets and restrictions on their own packages, the existing solution is for enterprises to build their own NPM warehouses. Fortunately, NPM itself is open source, both its server side and its client side. Building your own repository from source is no secret. The way to build a local NPM repository is almost the same as the way to build a mirror site (see Appendix D for details). The difference from mirror repositories is that enterprise local NPM can choose not to synchronize packages in official source repositories. Figure 2-10 is a schematic diagram of the mixed use of official warehouses and local warehouses in an enterprise. Figure 2-10 Schematic diagram of mixing official warehouses and local warehouses For internal enterprises, private reusable modules can be packaged into local NPM warehouses, so as to maintain the centralization of updates and prevent each small project from maintaining its own Modules with the same function prevent code sharing by copying and pasting. 2.6. 5 NPM Potential Issues NPM is handy as a tool for serving modules and packages. It's essentially a package sharing platform where anyone can contribute modules and package them to share, and they can also be used for free under licenses (mostly MIT licenses). These conveniences provided by NPM link modules to a shared platform, shortening the distance between contributors and users, which is very beneficial to the dissemination of modules, which is also very beneficial to the promotion of Node. There is hardly a language or platform where Node has thousands of third-party modules in just over 3 years. Part of this credit goes to Node's choice of JavaScript, a language with a huge developer base and great productivity, and part to the CommonJS specification and NPM, which allow products to be better organized, disseminated, and used. The potential problem is that on the NPM platform, everyone can share packages on the platform, and the quality of the packages on it varies depending on the level of developers. Another problem is that Node code can run on the server side, and security issues need to be considered. For package users, package quality and security issues need to be used as a criterion for whether or not to adopt a module. Although NPM does not have a rigid way to judge the quality and safety of a package, fortunately the open source community also has its inherent healthy development mechanism, which is the word-of-mouth effect, among which the NPM module homepage ( The dependency list on https://npmjs.org/ ) can illustrate the quality and reliability of the module. The second place to check the quality is GitHub. Most of the packages in NPM are hosted through GitHub. The number of observers and branches of a module project can also reflect the reliability and popularity of this module from the side. The third place to consider the quality of the package is the status of the test cases and documentation in the package. A package without unit testing is basically untrustworthy, and a package without documentation will make users feel uneasy when using it. In terms of security, after checking the quality of the modules, it should be possible to remove more than half of the candidate packages. Based on the fact that most of the users are JavaScript programmers, the difficulty actually exists in the third-party C/C++ extension modules. It is recommended that such modules are allowed to be used after being checked by the security department of the enterprise. In fact, in order to solve the above problems, Isaac Z. Schlueter plans to introduce the Kwalitee style in the CPAN community to make modules order natural. Kwalitee is an onomatopoeia, pronounced the same as quality. The original definition of it by the CPAN community is as follows: "Kwalitee" is something that looks like quality, sounds like quality, but is not quite quality. The general meaning is that it is not so easy to confirm whether the quality of a module is excellent. It can only be determined from some appearances. Take the test, but even if the test passes, it is not sure that it is a high-quality module. This method can eliminate most of the unqualified modules, although it is not accurate but effective. In general, the conditions to be met by modules that meet Kwalitee are roughly the same as those mentioned above. Have a good test. Has good documentation (README, API). Have good test coverage. Have good coding practices. more conditions. The CPAN community has developed quite a few specifications to examine modules. In the future, the NPM community will also have more specifications to examine modules. Readers can distinguish between good modules and bad modules according to these terms.
Reprinted from: http://book.douban.com/reading/29343648/

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327040954&siteId=291194637