🎉好用的🌹跨平台 nodejs 脚本库,你可以放弃 shell 了😭

1,550 阅读1分钟

shelljs 是一个使用 nodejs 实现的跨平台脚本库,实现了大部分类 unix 的 shell 命令,可以快速方便的实现跨平台的脚本操作(微软,说的就是你!!!).

具体就是利用 nodejs 提供的 api 能力复制实现了常用的 shell 命令.

cat、cd、chmod、octal、chmod、cp、pushd、popd、dirs、echo、exec、find、grep、head、ln、ls、mkdir、mv、pwd、rm、sed、replacement、set、sort、tail、tempdir、test、touch、uniq、which、exit、env 及对结果 pipe 操作。

shelljs 每个命令都是单独的 js 文件,我们有个需要把它打成一个文件作为本地依赖,看了下源码,需要改造下,实现如下.

// ./src/index.js

require('./commands').forEach(function (command) {
    require('./' + command);
});
exports.exit = process.exit;
exports.error = require('./error');
exports.env = process.env;
var common = require('./common');
Object.keys(common).forEach(function (fn) {
    if (fn !== 'shell') exports[fn] = common[fn];
});
var shell = common.shell;
Object.keys(shell).forEach(function (fn) {
    exports[fn] = shell[fn];
});

\


\
// webpack.js

const path = require('path');
const CircularDependencyPlugin = require('circular-dependency-plugin');
module.exports = {
    entry: path.resolve(__dirname, 'src'),
    output: {
        filename: 'sh.js',
        path: path.resolve(__dirname, 'dist'),
        library: {
            type: 'commonjs2',
        },
    },
    mode: 'development',
    devtool: 'source-map',
    target: 'node',
    plugins: [
        new CircularDependencyPlugin({
            exclude: /node_modules/,
            failOnError: true,
            allowAsyncCycles: false,
            cwd: process.cwd(),
        }),
    ],
    stats: 'verbose',
};

zx

google 基于 shelljs 的基础上实现了更方便的脚本操作,最终效果更像是脚本了,(shelljs 还是更像 js 函数代码一些),不过 google 使用了顶层 await 功能,所以需要 node 版本大于 14.3.0

#!/usr/bin/env zx

await $`cat package.json | grep name`

let branch = await $`git branch --show-current`
await $`dep deploy --branch=${branch}`

await Promise.all([
  $`sleep 1; echo 1`,
  $`sleep 2; echo 2`,
  $`sleep 3; echo 3`,
])

let name = 'foo bar'
await $`mkdir /tmp/${name}`

shx

$ shx pwd                       # ShellJS commands are supported automatically
/home/username/path/to/dir

$ shx ls                        # files are outputted one per line
file.txt
file2.txt

$ shx rm *.txt                  # a cross-platform way to delete files!

$ shx ls

$ shx echo "Hi there!"
Hi there!

$ shx touch helloworld.txt

$ shx cp helloworld.txt foobar.txt

$ shx mkdir sub

$ shx ls
foobar.txt
helloworld.txt
sub

$ shx rm -r sub                 # options work as well

$ shx --silent ls fakeFileName  # silence error output

shx 可以在命令行使用 shelljs 提供的函数功能.