When working on a client infrastructure project, you need to use JS to call command line to execute shell scripts. Here is a brief introduction and summary of shell commands and JS to execute shell commands.
Preface
Generally, in projects with pure front-end static pages, JS command line operations are not required. Usually, there may be such requirements in Node projects or Electron client projects. (The client framework of the electron itself has many methods of node built-in). Therefore, the following is about how the shell is executed for projects with node layers.
Let’s first understand what a shell is?
The shell in Linux/Unix, translation means 'shell'; shell provides an interface for users to interact with the kernel. It receives commands entered by the user and sends them to the kernel of the operating system for execution.
1. Command line
Users directly execute shell commands on the shell interface, writing lines in a row, and rarely write out a complete set of programs to execute, so it is called a command line.
2. Shell script
The user writes a sh script file in advance and then executes the script using a shell program. This method is called shell programming.
Introduction to several ways to adjust the shell (not limited to these)
- child_process: a child process api of node, which can create a child process to execute command line
- shelljs: a shell execution plugin based on node-based API encapsulation
- simple-git: A git command execution plugin based on node-based ap encapsulation
Let's find out in turn
1、child_process
introduce
child_process is a child process AP provided by node, which can be seen in detail.Official website、Chinese websiteRegarding the introduction of this type of API, there are very detailed descriptions of derivative shells and parameters. The following are two commonly used APIs.
1. child_process.exec(command[, options][, callback])
command: The shell command to run
Create a new shell process and execute command
2. child_process.execFile(file[, args][, options][, callback])
file: The file name or path to run, and the parameters are passed in as an array
Directly create executable files as new processes; you need to write .sh files separately, which can write complex logic, but there will be compatibility issues when using them on Windows (in addition, there are child_process.spawn() and other options to choose from)
Example
const util = require('util'); const child_process = require(‘child_process'); // Call the method and return a promise, such as const { stdout, stderr } = await exec('rm -rf build')const exec = (child_process.exec); const appPath = join(__dirname, 'app'); const runClean = async function () { // cwd specifies the current working directory of the child process. Here rm -rf build is to delete a folder under the specified directory. await exec(`rm -rf build`, { cwd: appPath }); await exec(`rm -rf test`, { cwd: appPath }); runClean();
2、shelljs
introduce
shelljs is an extension of j based on node API, and to introduce plugins: (npm address); It is more compatible than the native child_process and is more flexible to use, and the usage rate of this plugin is very high.
Tips:
This plug-in can not only call .exec to execute shell commands, but also encapsulate some shortcut operation instructions. For details, please refer to the github address.
cat Returns the file content
Const mdres = (‘*.md')
pwd get the current directory
const res = ();
find
find(‘src', ‘lib'); find([‘src', ‘lib']); // same as above find('.').filter(function(file) { return (/.js$/); });
mkdir create directory
mkdir('-p', ‘/tmp/a/b/c/d', ‘/tmp/e/f/g'); mkdir('-p', ['/tmp/a/b/c/d', ‘/tmp/e/f/g']); // same as above
Example
const shell = require(‘shelljs'); …… ('/update-git', function (req, res, next) { // If the directory exists, perform the Git pull operation. Otherwise, create a new directory and perform the git clone operation. if ((`${root}/${groupName}/${name}`)) { ('git pull', { cwd: `${root}/${groupName}/${name}`, }); } else { (`git clone ${remote} ${name}`, { cwd: `${root}/${groupName}`, }); } …… });
3、simple-git
In view of the previous example, executing shell scripts to operate git is actually very inconvenient to write complex git command statements. Finally, I introduced a plug-in specially designed for git: simple-git(npm address)
introduce
- After introducing plug-ins in the project, call simple-git/promise to perform asynchronous git operations, which is convenient for use with async/await
- It encapsulates and supports many git methods, such as clone, commit, status, pull, etc., and pass in cmd commands and parameters.
- You can even use() to parse the git commands entered by the front end
Example
The following is the client project communicates through IPC and processes git requests
const simpleGit = require('simple-git/promise'); ...... // Simple-git function that performs client simulation('simple-git', async function (e, { projectPath, cmd, args }) { const git = simpleGit(projectPath); try { const res = await git[cmd](...args); return res; } catch (e) { ('An error occurred while executing the simple-git command', { projectPath, cmd, args }, e); throw e; } });
Summarize
The above introduces the concept of shell and three ways to execute shell commands by js (only simple commands are listed here, and you can actually write .sh files as needed, pass parameters relative paths, and execute more complex shell scripts); in general, there are the following points:
- The shell is an interface for users to interact with the kernel. We can operate on native files, processes, etc. by executing shell command lines or scripts.
- There are many ways to execute shell commands for js. Here are several node-based methods:
- child_process native nodeAPI, you need to select models as needed
- A plug-in for shelljs Node, with good compatibility
- simple-git: A plug-in specially created for git commands, lightweight and easy to use
This is the article about several ways (Node) to execute shell commands by js. For more related content of js, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!