Shelljs – Unix shell commands for Node.js
Shelljs is a scripting language parser in Node.js, with rich and powerful permissions for underlying operations (Windows/Linux/OS X). Shelljs is essentially a layer of command encapsulation plug-in based on Node, allowing front-end developers to write shell commands directly in the most familiar javascript code to achieve functions without relying on Linux or conversion tools like CMder.
-
To solve the problem
Shell scripts are familiar from the front end, and they are already used in package.json configuration with the “build”: For example, “umi build && node zip.config.js”, NPM run build first executes umi build and then executes the zip.config.js script. Generate build folder and use easyZip to compress package, else exists build folder, generate ZIP package or other files required by the company. What Shelljs does is automate, freeing itself from time-consuming, repetitive routines to improve productivity and mood.
-
The basic grammar
Var shell = require('shelljs') // Check if the console starts with a command that starts with 'git'if(! shell.which('git'Shell. Echo (shell.'Sorry, this script requires git'); shell.exit(1); } shell.rm('-rf'.'out/Release'); // force recursion to delete 'out/Release' shell.cp('-R'.'stuff/'.'out/Release'); // Copy all contents of 'stuff/' to 'out/Release' directory shell.cd('lib'); // Go to the 'lib' directory // find all files with extension js, and iterate through the operation shell.ls('*.js').forEach(function(file) {/* This is the first difficult point: sed stream editor, recommended topic learning, -i means direct source file */ // replace the build_version field with'v0.1.2' shell.sed('-i'.'BUILD_VERSION'.'v0.1.2', file); // Remove the line containing the 'REMOVE_THIS_LINE' string from shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, ' ', file); // Replace the line containing the 'REPLACE_LINE_WITH_MACRO' string with the contents of 'macro.js' shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file); }); // return to the directory shell.cd('.. '); Run external tool synchronously // Run external tools synchronously //if (shell.exec('git commit -am "Auto-commit"').code ! == 0){ shell.echo('Error: Git commit failed'); shell.exit(1); } Copy the code
-
Example explanation
- shell.which(command)
Find the address of the specified command in the environment variable PATH, check whether the command can be executed, and return the absolute address of the command
-
echo
To (index.txt) is written to the file in the console output
-
Exit (code) Exits the current process with the exit code as the code
-
Rm ([options,] file [, file…] )
Delete one or more files or directories from a directory. Once deleted, it cannot be recovered.
Common parameters:
- -f: forcibly deletes a file.
- -i: Ask the user before deleting the vm.
- -r: indicates the directory for recursive processing.
- -v: displays the processing process.
shell.rm('-rf', staticSplash); Copy the code
-
cp([options,] source_array, dest) cp(‘-R’,’index.txt’, ‘~/newCopy/’) cp(‘-R’,[‘index.txt’, ‘old.txt’], ‘~/newCopy/’)
Used to copy one or more source files or directories to a specified file or directory.
Common parameters:
- -f:force (default behavior)
- -L: follow symlinks
- -r,-R: recursive
- -n: no-clobber
- -u: only copy if source is newer than dest
- -P: don’t follow symlinks
-
cd
Switches the working directory to the specified relative or absolute path. cd.. To return to the previous level, CD – goes back to the previous directory.
-
ls
Used to display a list of targets.
Common parameters:
- -a: displays all files.
- -c: displays query results in multiple columns.
- -l: displays the query results in a single column format (opposite to -c).
- -r: indicates the directory for recursive processing.
- -a: All files (including the initial files., except. And..)
- -d: Lists the directory itself, not its contents
ls(path.join('bundle'.'css/')).forEach(cssName => { *** }) Copy the code
-
sed([options,] search_regex, replacement, file_array
Replace the content in file_array that conforms to search_regex with replacement, supporting the capture group self-reference of the re. Process one line at a time, send the buffer content to the screen, and then process the next line until the loop ends.
Common parameters:
- -i: directly affects the source file
-
cat([options,] file [, file …] )
Read in the contents of one or more files, read in one file when specified, and read together when specifying multiple files.
Available options: -n: number all output lines
-
exec(command [, options] [, callback])
Execute the incoming command
- Async: whether to execute asynchronously. The default value is false
- Slient: does not output information to console. Default is false
- The default utf8 encoding:
Unless otherwise noted, command synchronously executes a given. In synchronous mode, it returns a ShellString (compatible with ShellJS V0.6. x, which returns the object of the form {code:… , stdout:… , stderr:… }). Otherwise, this returns the child process object and callback gets the parameters (code, stdout, stderr).
Note: For long-running processes, it is best to run exec() asynchronously
-
chmod
Set file call permission
- -c: Output a diagnostic for every file processed
- -v: like verbose, but report only when a change is made
- -R: change files and directories recursively
U indicates the owner of the file, G indicates the same group, O indicates others, A indicates all + indicates added permission, – indicates cancelled permission, = indicates unique permission. R indicates readable, W indicates writable, x indicates executable, and x indicates that the file is a subdirectory
chmod(755, '/Users/brandon'); chmod('755'.'/Users/brandon'); // same as above chmod('u+x'.'/Users/brandon'); chmod('-R'.'a-w'.'/Users/brandon'); Copy the code
-
Pushd ([options] [dir | ‘-n’ | ‘+ N])
Available option -n: Disables normal directory changes when adding directories to the stack so that only the stack is manipulated
parameter
- Dir: Make the current working directory the top of the stack, then perform the equivalent CD dir
- +N: Rotate the stack to move the NTH directory (starting from zero on the left side of the dirS printed list) to the top of the list
- -n: Rotates the stack to rotate the NTH directory (counting from zero starting to the right of the dirS printed list) to the top of the list
echo(process.cwd()); // Current file parent path /Users...pushd('/etc') // /private/etc /Users... pushd('+ 1') // users... /private/etc Copy the code
Save the current directory at the top of the directory stack, and then CD to dir. Pushd swaps the first two directories with no arguments. Returns an array of paths on the stack.
-
The popd ([options] [‘ -n ‘|’ + N])
Available options: -n: Disables normal directory changes when removing a directory from the stack so that only the stack is operated on
Parameters:
- +N: Delete the NTH directory (counting from the left of the dirS printed list), starting from zero
- -n: Deletes the NTH directory (calculated from the right of the list printed by the dirS).
echo(process.cwd()); // '/usr' pushd('/etc'); // '/etc /usr' echo(process.cwd()); // '/etc' popd(a); //'/usr' echo(process.cwd()); // '/usr' Copy the code
If no argument is given, POPd will remove the top-level directory from the stack and execute CD to the new top-level directory. Starting with the first directory listed by dirs, the elements are numbered from 0; So popd is the same thing as popd plus 0. Returns an array of paths on the stack
-
Dirs ([options | ‘+ N’ | ‘-n’]
Available options: -c: Clears the directory stack by removing all elements
Parameters:
- +N: Displays the NTH directory (counting from the left side of the list printed by dirs when called without options), starting from zero
- -n: Displays the NTH directory (counting from the right of the list printed by dirs when called without options), starting from zero
Displays a list of currently remembered directories. Returns an array of paths on the stack, or a single path if + N or -n is specified.
-
Find (path [, path…]) )
Find files
console.log(find('.. /Config/application.js')) Copy the code
Return path_array
-
Grep ([options,] regex_filter, file [, file…] )
Instead of fing finding files, grep is used to find content
Available options:
- -v: reverses the meaning of the regular expression and prints unqualified lines
- -l: Prints only the names of matching files
grep('-v'.'GLOBAL_VARIABLE'.'*.js'); grep('GLOBAL_VARIABLE'.'*.js'); Copy the code
Reads the input string from the given file and returns a string containing all lines of the file regex_filter that matches the given file
-
Head ([{‘ -n ‘:},] file [, file… )
Read the beginning of the file
Available options: -n: displays the first line of the file
console.log(head('bundle.js')) console.log(head({'-n': 1}.'bundle.js') // Get the first lineCopy the code
-
Tail ([{‘ -n ‘:},] file [, file…] )
Read the end of the file
Available options: -n: displays the last few lines of the file
var str = tail({'-n': 1}.'file*.txt'); var str = tail('file1'.'file2'); var str = tail(['file1'.'file2']); // same as above Copy the code
-
Ln ([options,] source, dest)
Create links
ln('file'.'newlink'); // /Users... /newlink ln('-sf'.'file'.'newlink'); // If newlink exists, force link 🔗Copy the code
-
Mkdir ([options,] dir [, dir…] )
Creating a folder
Available options: -p: full path (intermediate directory will be created if necessary
shell.mkdir('bundle') shell.mkdir('-p'['bundle'.'js']) Copy the code
-
Touch ([options,] file [, file…] )
Unlike mkdir, which creates folders, touch creates files
Available options:
- -a: Changes only the access time
- -c: Do not create any files
- -m: Changes only the modification time
- -d DATE: specifies the time
- -r FILE: Replaces the time of the new FILE with the time of the FILE
-
Mv ([options,] source [, source…] The dest ‘)
mobile
Available options:
- -f: force (Default behavior)
- – n: no – clobber
mv('move'.'target'); // Move the move file to the target folderCopy the code
-
The PWD ()
Viewing the Current Directory
-
Set (option)
Set global configuration variables
Available options:
- +/-e: Exit on error (config.fatal)
- +/-v: verbose: show all commands (config.verbose)
- +/-f: Disable filename extension (globbing)
set('-e'); // exit upon first error set('+e'); // this undoes a "set('-e')" Copy the code
-
Sort ([options,] file [, file…] )
Content sorting
Available options:
- -r: reverses the comparison result
- -n: Compares by value
sort('foo.txt'.'bar.txt'); sort('-r'.'foo.txt'); Copy the code
Returns the contents of the file, sorted line by line. Sort multiple
-
The test ()
File type judgment
Available options: ‘-b’, ‘path’ : true ‘-c’ if path is a block device, ‘path’ : true ‘-d’ if path is a character device, ‘path’ : true ‘-e’ if path is a directory, ‘path’ : True ‘-f’ if path exists, ‘path’ : true ‘-l’ if path is a regular file, ‘path’ : true ‘-p’ if path is a symbolic link, ‘path’ : True ‘-s’ if path is a pipe (FIFO),’ PATH ‘: true if path is a socket
if (!test('-f', path)) continue; Copy the code
-
Uniq ([options,] [input, [output]]
Available options:
- -i: case is ignored during comparison
- -c: Lists prefixes according to the number of occurrences
- -d: Prints only duplicate lines. Each line corresponds to one line
-
ShellString()
Constructor that converts a string to a Shell string that supports chaining calls to special Shell commands
ShellString('hello world') Copy the code
-
ShellString.Prototype.to()
Outputs shellString to the specified file, equivalent to > in scripting languages
-
ShellString.Prototype.toEnd()
Appends shellString to specified file, equivalent to >> in scripting language
-
env[‘VAR_NAME’]
Point to the process. Env
-
Pipes Chain call support
Sed, grep, cat, exec, to support chain calls toEnd
-
Configuration
- config.silent
sh.config.silent
- config.fatal
config.fatal
- config.verbose
config.verbose
- config.globOptions
config.globOptions
- Config.reset () resets the global Settings
shell.config.reset()
- config.silent
Refer to the link
Shelljs official website documentation