shelljs - Node.js中的便携式Unix shell命令

ShellJS - Unix shell commands for Node.js

ShellJS is a portable (Windows/Linux/OS X) implementation of Unix shell commands on top of the Node.js API. You can use it to eliminate your shell script's dependency on Unix while still keeping its familiar and powerful commands. You can also install it globally so you can run it from outside Node projects - say goodbye to those gnarly Bash scripts!

Global vs. Local

We no longer recommend using a global-import for ShellJS (i.e. require('shelljs/global')). While still supported for convenience, this pollutes the global namespace, and should therefore only be used with caution.

Alters the permissions of a file or directory by either specifying the absolute permissions in octal form or expressing the changes in symbols. This command tries to mimic the POSIX behavior as much as possible. Notable exceptions:

In symbolic modes, a-r and -r are identical. No consideration is given to the umask.

When no arguments are given, popd removes the top directory from the stack and performs a cd to the new top directory. The elements are numbered from 0, starting at the first directory listed with dirs (i.e., popd is equivalent to popd +0). Returns an array of paths in the stack.

dirs([options | '+N' | '-N'])

Available options:

-c: Clears the directory stack by deleting all of the elements.

-q: Supresses output to the console.

Arguments:

+N: Displays the Nth directory (counting from the left of the list printed by dirs when invoked without options), starting with zero.

-N: Displays the Nth directory (counting from the right of the list printed by dirs when invoked without options), starting with zero.

Display the list of currently remembered directories. Returns an array of paths in the stack, or a single path if +N or -N was specified.

Executes the given commandsynchronously, unless otherwise specified. When in synchronous mode, this returns a ShellString. Otherwise, this returns the child process object, and the callback receives the arguments (code, stdout, stderr).

Not seeing the behavior you want? exec() runs everything through sh by default (or cmd.exe on Windows), which differs from bash. If you need bash-specific behavior, try out the {shell: 'path/to/bash'} option.

Security note: as shell.exec() executes an arbitrary string in the system shell, it is critical to properly sanitize user input to avoid command injection. For more context, consult the Security Guidelines.

sed([options,] search_regex, replacement, file [, file ...])

sed([options,] search_regex, replacement, file_array)

Available options:

-i: Replace contents of file in-place. Note that no backups will be created!

Examples:

sed('-i', 'PROGRAM_VERSION', 'v0.1.3', 'source.js');

Reads an input string from files, line by line, and performs a JavaScript replace() on each of the lines from the input string using the given search_regex and replacement string or function. Returns the new ShellString after replacement.

Also, like unix sed, ShellJS sed runs replacements on each line from the input file (split by '\n') separately, so search_regexes that span more than one line (or inlclude '\n') will not match anything and nothing will be replaced.

set(options)

Available options:

+/-e: exit upon error (config.fatal)

+/-v: verbose: show all commands (config.verbose)

+/-f: disable filename expansion (globbing)

Examples:

set('-e'); // exit upon first errorset('+e'); // this undoes a "set('-e')"

Sets global configuration variables.

sort([options,] file [, file ...])

sort([options,] file_array)

Available options:

-r: Reverse the results

-n: Compare according to numerical value

Examples:

sort('foo.txt', 'bar.txt');
sort('-r', 'foo.txt');

Return the contents of the files, sorted line-by-line as a ShellString. Sorting multiple files mixes their content (just as unix sort does).

Evaluates expression using the available primaries and returns corresponding boolean value.

ShellString.prototype.to(file)

Examples:

cat('input.txt').to('output.txt');

Analogous to the redirection operator > in Unix, but works with ShellStrings (such as those returned by cat, grep, etc.). Like Unix redirections, to() will overwrite any existing file! Returns the same ShellString this operated on, to support chaining.

ShellString.prototype.toEnd(file)

Examples:

cat('input.txt').toEnd('output.txt');

Analogous to the redirect-and-append operator >> in Unix, but works with ShellStrings (such as those returned by cat, grep, etc.). Returns the same ShellString this operated on, to support chaining.

touch([options,] file [, file ...])

touch([options,] file_array)

Available options:

-a: Change only the access time

-c: Do not create any files

-m: Change only the modification time

{'-d': someDate}, {date: someDate}: Use someDate (instance of Date) instead of current time

{'-r': file}, {reference: file}: Use file's times instead of current time

Update the access and modification times of each file to the current time. A file argument that does not exist is created empty, unless -c is supplied. This is a partial implementation of touch(1). Returns a ShellString indicating success or failure.

which(command)

Examples:

var nodeExec =which('node');

Searches for command in the system's PATH. On Windows, this uses the PATHEXT variable to append the extension if it's not already executable. Returns a ShellString containing the absolute path to command.

exit(code)

Exits the current process with the given exit code.

error()

Tests if error occurred in the last command. Returns a truthy value if an error returned, or a falsy value otherwise.

Note: do not rely on the return value to be an error message. If you need the last error message, use the .stderr attribute from the last command's return value instead.

ShellString(str)

Examples:

var foo =newShellString('hello world');

This is a dedicated type returned by most ShellJS methods, which wraps a string (or array) value. This has all the string (or array) methods, but also exposes extra methods: .to(), .toEnd(), and all the pipe-able methods (ex. .cat(), .grep(), etc.). This can be easily converted into a string by calling .toString().