We are familiar with command programs. When we start the front-end project, entering NPM run serve in the terminal is to enter a command program; At the terminal type NPM run build is also a command program.

But what does the terminal do after receiving the command? That’s the purpose of this article, showing you how the Node command has already been built.

Build an executable step

Start by creating a new Hello file and writing something to it

#! /usr/bin/env node
console.log('hello node shell demo')
Copy the code

Then execute node./hello

$ node ./hello
hello node shell demo
Copy the code

If you execute./hello directly, you will be told that you do not have file execution permission

$ ./hello
zsh: permission denied: ./hello
Copy the code

Change the permission of Hello

$ chmod 755 hello
Copy the code

Perform. / hello

$ ./hello
hello node shell demo
Copy the code

After file authorization, the./hello execution essentially still executes Node./hello

So, every time I do this, I have to find a path, and I’m going to do it a different way without writing a path.

Create a package.json file in the current directory

{
    "name": "hello"."scripts": {
        "serve": "node hello"}}Copy the code

Then execute NPM run serve and we get the same result.

$ npm run serve
hello node shell demo
Copy the code

Here we implement an NPM Script step, but one step short of the actual step, omitting the Node field in the command. Next modify package.json

{
    "name": "hello"."bin": {
        "hello": "hello"
    },
    "scripts": {
        "serve": "hello"}}Copy the code

Then run the NPM link command

$ npm link
Copy the code

Finally, run NPM run serve

$  npm run serve
hello world
Copy the code

Explanation:

#! /usr/bin/env node: The convention is written on the first line of the script to indicate that the script file is being executed in the Node environment

Chomd 755: chmod is used to set file permissions in Linux. Chmod 755 sets the user permissions to be readable, writable, and executable by the file owner

NPM link: connect the project to the global node_modules, so that this command can be used in other projects.

Bin: stores NPM executable scripts. In actual projects, executable scripts are stored in the node_molues/. Bin directory.

Executable script parameters

Command line arguments can be obtained using the system variable process.argv.

#! /usr/bin/env node
console.log('hello ', process.argv[2]);
Copy the code

Perform the hello param

$ hello param
hello param
Copy the code

Summary: in practice, when we run NPM serve to start the project, we actually execute the build file corresponding to serve in node_modules/. Bin, for example, the file is hello. In the vue project, vue-cli-service is executed, and vue-cli-servce is followed by the script parameters.