How to use shell scripts in node

How to use shell scripts in node

background

During development, we may need some scripts to batch process our business logic in certain situations. How to call shell scripts in nodejs?

New

Create a new script file under the project

touch newFile.sh

Modify file permissions

chmod 777 newFile.sh changes the file to be readable, writable and executable

Nodejs call

File Reading

//Use the file reading method in the child process of nodejs const { execFile } = require('child_process');

Example

DocsService.publishAllDocs = (req, res) => {
 req.session.touch();
 const { docName, pathName, saveDocsList, docType } = req.body;
 var docText = req.body.docText;
 var newGit = req.body.newGit;
 //Get the file path var filepath = path.join(__dirname, '../../bin/rnsource/publishAllDocs.sh');
 var fileArr, fileName, spath, dirnameBack, docbackList = [], docbackPath, docPath = "";
 var username = req.session.user_name;
 var str = docName+'/'+ pathName + '|'+ username;
 var reg = new RegExp(`^(${str})`);
 saveDocsList.map((item, index)=>{
   fileArr = item.pathName.split("/");
   fileName = fileArr[fileArr.length-1];
   if(docType == "docsify"){
     dirnameBack = fileName != "" ? `../../gitlib/docBackup/${docName}/docs/${item.pathName}`:`../../gitlib/docBackup/${docName}/docs/README.md`
   }else{
     spath = item.pathName.split(fileName)[0];
     dirnameBack = spath != "" ?'../../gitlib/docBackup/'+ docName+'/'+ spath +'/'+fileName:'../../gitlib/docBackup/'+ docName+'/' + fileName; 
   }

   docbackPath = path.join(__dirname, dirnameBack);
   docbackList.push(docbackPath);
   docPath += docbackPath + " ";
 })
 docPath += ""
 //cwd sets the current path. What I set here is the current location of the nodejs code js execFile(filepath, [docName, docPath, docType], { cwd: '.' }, function(err, stdout, stderr){
   logger.info(stdout);
   if(err){
     loggerFileError({user:username,docName:docName,pathName:'all',operate:"gitbook file one-click release",err});
     res.json({
       respCode: -1,
       errMsg: "One-click publishing failed"
     })
   }else{
     res.json({
       respCode: 0,
       msg: "One-click publishing successful"
     })
     gitPush({ docName, fileName, docbackPath: docbackList, username, pathName, docType })
     unblockFile({ docName, username, pathName, reg });
   }
 }) 
}

Callbacks

Successful execution will return the command executed by the script

execFile

  • The first parameter: the external program to be called, here is the file to be read
  • Second parameter: parameters passed to the external program (must be placed in an array)
  • The third parameter: callback function, in which the execution result of the external program can be returned

shell

publishAllDocs.sh Note: All the instructions here are shell scripts for non-windows. The .bat scripts for windows are not explained here.

#$1 The outermost directory of the document$2 The name of the currently modified file$3 The directory of the currently modified filecd $(pwd)/gitlib/docs/$1
echo "come in"
for item in $2; do
  echo "${item}"
  cp -f ${item} ${item/docBackup/docs}
done
# echo "initialization entry"
echo "$(pwd)/gitlib/docs/$1"
if [ "$3" == "docsify" ]; then
  #Copy the files in the specified directory, such as: $1/$3/$2 docs/cst/7e4ce1de04621e0b/
  #Such as cp -rf ../../docBackup/wireless/docs/cst/7e4ce1de04621e0b/10708d589eedfffd.md ./docs/cst/7e4ce1de04621e0b/
  cp -rf ./docs ../../../public/docs/$1
else
  # Process gitbook type documents gitbook build
  echo "Copy document"
  cp -rf ./_book/* ../../../public/docs/$1
fi

Parameter reception

  • Get parameters based on the data passed during business calls
  • Use "$" directly to get
  • The order of acquisition is the order in which data is passed in.
  • Remember that the first parameter of the array is not the value of the array subscript.

Use of for loop

Use the for...in form in the shell

Example of loop body data that needs to be looped

"/Users/Desktop/work/docManager/docServer/gitlib/docBackup/mygitbook/docs/d09985fc67088b35/d09985fc67088b35.md /Users/Desktop/work/docManager/docServer/gitlib/docBackup/mygitbook/docs/d09985fc67088b35/d09985fc67088b35/6f7a2c61c9bac0a3.md /Users/Desktop/work/docManager/docServer/gitlib/docBackup/mygitbook/README.md /Users/Desktop/work/docManager/docServer/gitlib/docBackup/mygitbook/docs/d09985fc67088b35/d09985fc67088b35/6f7a2c61c9bac0a3.md "

The data in the loop body of the shell script is special and is not our regular array or json

It is a string separated by spaces, such as: "abcde"

## $2 is the data received in the script and spliced ​​in the format as shown in the data example above## Use for...in in a loop. Remember to add do after it to execute the loop body and end the loop with done## Each sub-item of the item loop body is as follows: /Users/Desktop/work/docManager/docServer/gitlib/docBackup/mygitbook/docs/d09985fc67088b35/d09985fc67088b35.md
for item in $2; do
  echo "${item}"
  cp -f ${item} ${item/docBackup/docs}
done
## ${item/docBackup/docs} string replacement## Here, docBackup in the item path is replaced with docs. For detailed explanation, please see the shell string replacement below

Shell specified string replacement

In JS, we can use replace to replace strings, so how do we implement it in shell?

Example:

string "abc12342341"

  • echo ${string/23/bb} //abc1bb42341 replace once
  • echo ${string//23/bb} //abc1bb4bb41 Double slash replaces all matches
  • echo ${string/#abc/bb} //bb12342341 #What to start with to match, the root ^ in php is a bit like
  • echo ${string/%41/bb} //abc123423bb % ends with something to match, the root $ in PHP is a bit like

Use of if conditional judgment

grammar

if[];then
 ...
else
 ...
fi

Example

## Conditional judgment uses [] instead of ()
## [] should be added after;
if [ "$3" == "docsify" ]; then
  #Copy the files in the specified directory, such as: $1/$3/$2 docs/cst/7e4ce1de04621e0b/
  #Such as cp -rf ../../docBackup/wireless/docs/cst/7e4ce1de04621e0b/10708d589eedfffd.md ./docs/cst/7e4ce1de04621e0b/
  cp -rf ./docs ../../../public/docs/$1
else
  # Process gitbook type documents gitbook build
  echo "Copy document"
  cp -rf ./_book/* ../../../public/docs/$1
fi

Notice

  • The string in the conditional judgment should use double quotes
  • If there are variables (strings) in the conditional judgment, the variables should also be enclosed in double quotes.
  • The conditional judgment [] must be followed by ; and then must be used to continue execution.
  • The conditional judgment should end with fi

This is the end of this article about the methods and steps of using shell scripts in node. For more relevant content about using shell scripts in node, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Usage of Node.js http module
  • Nodejs Exploration: In-depth understanding of the principle of single-threaded high concurrency
  • Understanding what Node.js is is so easy
  • Specific use of node.js global variables
  • AsyncHooks asynchronous life cycle in Node8
  • Nodejs error handling process record
  • The whole process of node.js using express to automatically build the project
  • The core process of nodejs processing tcp connection
  • Detailed explanation of Nodejs array queue and forEach application
  • Comparing Node.js and Deno

<<:  Linux kernel device driver character device driver notes

>>:  How to enable MySQL remote connection in Linux server

Recommend

How to write a picture as a background and a link (background picture plus link)

The picture is used as the background and the lin...

Common methods of Vue componentization: component value transfer and communication

Related knowledge points Passing values ​​from pa...

Docker connects to a container through a port

Docker container connection 1. Network port mappi...

The use and methods of async and await in JavaScript

async function and await keyword in JS function h...

Nginx configuration and compatibility with HTTP implementation code analysis

Generate SSL Key and CSR file using OpenSSL To co...

Vue uses mixins to optimize components

Table of contents Mixins implementation Hook func...

The difference between hash mode and history mode in vue-router

vue-router has two modes hash mode History mode 1...

Mini Program to Implement Sieve Lottery

This article example shares the specific code of ...

Linux server SSH cracking prevention method (recommended)

1. The Linux server configures /etc/hosts.deny to...

Vue3 implements CSS infinite seamless scrolling effect

This article example shares the specific code of ...

Vue's vue.$set() method source code case detailed explanation

In the process of using Vue to develop projects, ...