Home > Web Front-end > JS Tutorial > body text

How to use node.js command line tools correctly

php中世界最好的语言
Release: 2018-05-30 14:37:30
Original
1585 people have browsed it

This time I will bring you how to use the node.js command line tool correctly, and what are the precautions on how to use the node.js command line tool. The following is a practical case. Let’s take a look.

1. First understand package.json

The root directory of each project has a package.json The file defines the various modules required for this project, as well as the project configuration information. The following is a relatively complete package.json file

{
 "name": "vue-cli",
 "version": "2.9.3",
 "description": "A simple CLI for scaffolding Vue.js projects.",
 "preferGlobal": true,
 "bin": {
 "vue": "bin/vue",
 "vue-init": "bin/vue-init",
 "vue-list": "bin/vue-list"
 },
 "repository": {
 "type": "",
 "url": ""
 },
 "keywords": [
 ],
 "author": "litongqian",
 "license": "MIT",
 "bugs": {
 "url": ""
 },
 "homepage": "",
 "scripts": {
 "test": "npm run lint && npm run e2e",
 "start": "node index.js"
 },
 "dependencies": {
 "async": "^2.4.0",
 "chalk": "^2.1.0",
 },
 "devDependencies": {
 "chai": "^4.1.2",
 "eslint": "^3.19.0",
 },
 "engines": {
 "node": ">=6.0.0"
 }
}
Copy after login

1. The scripts field

specifies the npm command line abbreviation for running the script command. For example, start specifies the command to be executed when running npm run start.

2. bin field

The bin item is used to specify the location of the executable file corresponding to each internal command

"bin": {
 "vue": "bin/vue",
 "vue-init": "bin/vue-init",
 "vue-list": "bin/vue-list"
 },
Copy after login

The above code specifies, vue command The corresponding executable file is vue in the bin subdirectory.

3. npm link

When developing NPM modules, sometimes we want to try them out while developing, such as when debugging locally, <a href="http://www.php.cn/wiki/136.html" target="_blank"> require</a>('myModule') will automatically load modules under native development. Node stipulates that when using a module, it needs to be installed in the global or project node_modules directory. For modules under development, the solution is to generate a symbolic link in the global node_modules directory pointing to the module's local directory.

npm link will play this role and the symbolic link will be automatically created.

Please imagine a scenario where you develop a module myModule, the directory is src/myModule, and you want to use it in your own project myProject To this module, the project directory is src/myProject. First, run the npm link command under the module directory ( src/myModule ).

src/myModule$ npm link
Copy after login

The above command will generate a symbolic link file in the global module directory of NPM. The name of the file is the module name specified in the package.json file.

/path/to/global/node_modules/myModule -> src/myModule
Copy after login

At this time, the myModule module can be called globally. However, if we want to install this module in the project, we need to perform the following steps.

Switch to the project directory, run the npm link command again, and specify the module name.

src/myProject$ npm link myModule
Copy after login

The above command is equivalent to generating a symbolic link to the local module.

Copy code The code is as follows:

src/myProject/node_modules/myModule -> /path/to/global/node_modules/myModule

Then , you can load the module in your project.

var myModule = require('myModule');
Copy after login

In this way, any changes in myModule can be directly reflected in the myProject project. However, this also presents risks. Any modifications to myModule in the myProject directory will be reflected in the source code of the module.

If your project no longer needs this module, you can use the npm unlink command in the project directory to delete the symbolic link.

src/myProject$ npm unlink myModule
Copy after login

2. Executable script

Write a simple script hello

$ mkdir hello #Create a folder

$ cd hello && touch hello #Create command file

#!/usr/bin/env node
console.log('hello world');
Copy after login

Be sure to add the line #!/usr/bin/env node to the head of the file, which means using node as the explanation of the script Program and node paths are searched through env, which can avoid problems caused by different node installation paths.

Open /usr/bin/env, you can view the PATH, the operating system finds the node through the path

Then, modify hello permission.

$ chmod 755 hello
$./hello
Copy after login

如果想把 hello 前面的路径去除,可以将 hello 的路径加入环境变量 PATH。但是,另一种更好的做法,是在当前目录下新建 package.json ,写入下面的内容。

{
 "name": "hello",
 "bin": {
 "hello": "./hello"
 }
}
Copy after login

然后执行 npm link 命令。不明白的看上面

$ npm link
Copy after login

执行后会产生一个全局的映射关系,就可以全局使用hello命令了

三.命令行参数

命令行参数可以用系统变量 process.argv 获取。

修改hello脚本

#!/usr/bin/env node
console.log('hello ', process.argv);
Copy after login

其中process为node进程中的全局变量,process.argv为一数组,数组内存储着命令行的各个部分,argv[0]为node的安装路径,argv[1]为主模块文件路劲,剩下为子命令或参数,如下:

$ hello a b c

# process.argv的值为[ '/usr/local/bin/node', '/usr/local/bin/hello', 'a', 'b', 'c' ]

脚本可以通过 child_process 模块新建子进程,从而执行 Unix 系统命令,修改hello

exec 方法用于执行bash命令, exec 方法最多可以接受两个参数,第一个参数是所要执行的shell命令,第二个参数是回调函数,该函数接受三个参数,分别是发生的错误、标准输出的显示结果、标准错误的显示结果。

#!/usr/bin/env node
var name = process.argv[2];
var exec = require('child_process').exec;
var child = exec('echo hello ' + name, function(err, stdout, stderr) {
 if (err) throw err;
 console.log(stdout);
});
Copy after login

执行$ hello litongqian

如果我们想查看所有文件,修改hello

var name = process.argv[2];
var exec = require('child_process').exec;
var child = exec(name, function(err, stdout, stderr) {
 if (err) throw err;
 console.log(stdout);
});
Copy after login

执行$ hello ls 

hello目录下有三个文件

四、shelljs 模块

shell.js 模块重新包装了 child_process,调用系统命令更加方便。它需要安装后使用。

npm install --save shelljs
Copy after login

然后,改写脚本。

#!/usr/bin/env node
var name = process.argv[2];
var shell = require("shelljs");
shell.exec("echo hello " + name);
Copy after login

五、yargs 模块

shelljs 只解决了如何调用 shell 命令,而 yargs 模块能够解决如何处理命令行参数。它也需要安装。

$ npm install --save yargs
Copy after login

yargs 模块提供 argv 对象,用来读取命令行参数。请看改写后的 hello 。

#!/usr/bin/env node
var argv = require('yargs').argv;
console.log('hello ', argv.name);
Copy after login

使用时,下面两种用法都可以。

$ hello --name=tom
hello tom
$ hello --name tom
hello tom
Copy after login

也就是说,process.argv 的原始返回值如下。

$ node hello --name=tom
[ 'node',
 '/usr/local/bin/hell',
 '--name=tom' ]
Copy after login

yargs 可以上面的结果改为一个对象,每个参数项就是一个键值对。

六.发布命令包

通过npm publish进行发布,前提是有npm帐号。如何操作可以查看npm 官方文档。

本文是通过原生node.js来开发命令工具,而vue-cli是采用commander.js来简化命令工具开发,

了解了执行流程,去学习对应的模块,就很好知道原理了!,本文抛个砖头

 

最后:有时我们用到的命令行不是全局安装的,而是本地安装的

1. package.json bin字段

bin项用来指定各个内部命令对应的可执行文件的位置。

"name":"someTool",
"bin": {
 "someTool": "./bin/someTool.js"
}
Copy after login

上面代码指定,someTool 命令对应的可执行文件为 bin 子目录下的 someTool.js。

当一个项目依赖上面的someTool工具时,同时只是本地安装

{
 "name": "myproject",
 "devDependencies": {
 "someTool": "latest"
 },
 "scripts": {
 start: 'someTool build' //等同于start: './node_modules/someTool/someTool.js build'
 }
}
Copy after login

npm会寻找这个文件,在 node_modules/.bin/ 目录下建立符号链接。在上面的例子中,someTool.js会建立符号链接 npm_modules/.bin/someTool 。由于 node_modules/.bin/ 目录会在运行时加入系统的PATH变量,因此在运行npm时,就可以不带路径,直接通过命令来调用这些脚本。

因此,像上面这样的写法可以采用简写。

scripts: { 
 start: './node_modules/someTool/someTool.js build'
}
// 简写为
scripts: { 
 start: 'someTool build'
}
Copy after login

所有 node_modules/.bin/ 目录下的命令,都可以用 npm run [命令] 的格式运行。在命令行下,键入 npm run ,然后按tab键,就会显示所有可以使用的命令。

1. npm run

上面代码中, scripts 字段指定了两项命令 start ,输入 npm run-script start 或者 npm run start ,就会执行  someTool build 。 npm runnpm run-script 的缩写,一般都使用前者,但是后者可以更好地反应这个命令的本质。

npm run 命令会自动在环境变量 $PATH 添加 node_modules/.bin 目录,所以 scripts 字段里面调用命令时不用加上路径,这就避免了全局安装NPM模块。

npm run 如果不加任何参数,直接运行,会列出 package.json 里面所有可以执行的脚本命令。

npm内置了两个命令简写, npm test 等同于执行 npm run testnpm start 等同于执行 npm run start

npm run 会创建一个Shell,执行指定的命令,并临时将 node_modules/.bin 加入PATH变量,这意味着本地模块可以直接运行。

举例来说,你执行ESLint的安装命令。

$ npm i eslint --save-dev
Copy after login

运行上面的命令以后,会产生两个结果。首先,ESLint被安装到当前目录的 node_modules 子目录;其次, node_modules/.bin 目录会生成一个符号链接 node_modules/.bin/eslint ,指向ESLint模块的可执行脚本。

然后,你就可以在 package.jsonscript 属性里面,不带路径的引用 eslint 这个脚本。

{
 "name": "Test Project",
 "devDependencies": {
 "eslint": "^1.10.3"
 },
 "scripts": {
 "lint": "eslint ."
 }
}
Copy after login

等到运行 npm run lint 的时候,它会自动执行 ./node_modules/.bin/eslint .

如果直接运行 npm run 不给出任何参数,就会列出 scripts 属性下所有命令。

$ npm run
Available scripts in the user-service package:
 lint
  jshint **.js
 test
 mocha test/
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

React怎样在react-router路由实现登陆验证控制

Angular路由内路由守卫该如何使用

The above is the detailed content of How to use node.js command line tools correctly. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template