backgroundDuring development, we may need some scripts to batch process our business logic in certain situations. How to call shell scripts in nodejs? NewCreate 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 }); } }) } CallbacksSuccessful execution will return the command executed by the script execFile
shellpublishAllDocs.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
Use of for loopUse the for...in form in the shell Example of loop body data that needs to be looped
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 replacementIn JS, we can use replace to replace strings, so how do we implement it in shell? Example: string "abc12342341"
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
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:
|
<<: Linux kernel device driver character device driver notes
>>: How to enable MySQL remote connection in Linux server
Main library binlog: # at 2420 #170809 17:16:20 s...
Copy code The code is as follows: <!--doctype ...
The picture is used as the background and the lin...
Related knowledge points Passing values from pa...
Docker container connection 1. Network port mappi...
Table of contents question 1. Install webpack web...
async function and await keyword in JS function h...
Generate SSL Key and CSR file using OpenSSL To co...
Table of contents Mixins implementation Hook func...
vue-router has two modes hash mode History mode 1...
This article example shares the specific code of ...
Table of contents introduction 1. Code to start t...
1. The Linux server configures /etc/hosts.deny to...
This article example shares the specific code of ...
In the process of using Vue to develop projects, ...