使用Node.js进行Shell脚本编写

11

我想知道是否有任何Node框架或Node库可以用于编写shell脚本?例如,我有一个bash shell程序来安装Graphite和OpenTSDB RRD工具,我想使用node.js完成,这是可能的吗?

谢谢

3个回答

11

看看 shelljs - 它实现了类似shell和GNU coreutils的函数。与coffeescript一起使用,它可以非常类似于shell脚本:

if not which 'git'
  echo 'Sorry, this script requires git'
  exit 1

# Copy files to release dir
mkdir '-p', 'out/Release'
cp '-R', 'stuff/*', 'out/Release'

# Replace macros in each .js file
cd 'lib'
for file in ls '*.js'
  sed '-i', 'BUILD_VERSION', 'v0.1.2', file
  sed '-i', /.*REMOVE_THIS_LINE.*\n/, '', file
  sed '-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, cat 'macro.js', file
cd '..'

# Run external tool synchronously
if (exec 'git commit -am "Auto-commit"').code != 0
  echo 'Error: Git commit failed'
  exit 1

谢谢@Andrey Sidorov,看起来非常有前途,我打算尝试一下这个库。 - Nam Nguyen

3
你应该看一下Grunt,它是一个工具包,帮助人们在node.js中编写构建和其他脚本。有很多插件可以帮助你轻松地做一些有趣的事情。
话虽如此,如果你知道Bash,我会建议你坚持使用bash。
在Twitter上查看这个关于Bash与Grunt脚本的有趣的线程 我使用Grunt的原因
  • 运行Lint工具
  • 运行JS单元测试
  • 运行预处理器(sass,require.js,uglify等)
我使用Capistrano*的原因
  • 将代码部署到生产环境
我使用Bash**的原因
  • 设置服务器并运行它们等等

  • * capistrano + git或chef或其他
  • ** bash或任何其他你想使用的工具

1
请问您能否进一步解释为什么我已经了解Bash,但您仍然坚持使用它?相比Grunt,使用Bash有哪些优势呢? - Nam Nguyen
1
  1. 在异步JavaScript中执行二进制程序比在Bash中要困难得多。
  2. Grunt / node.js仍处于1.0之前,并且具有不断变化的API(grunt比node更多)。
  3. Bash是一种通用工具,可在许多系统上使用,而node.js和grunt不太可能安装在许多系统上。
- Jamund Ferguson
Docker https://www.docker.com/ 可以大大简化这一切,减少了很多不必要的麻烦。(** and *) - Quickredfox

2

有很多种选择,其中最受欢迎的是 commander

npm install --save commander

然后编写命令非常简单:
#!/usr/bin/env node

var program = require('commander');

program
  .version('0.0.1')
  .option('-f, --foo', 'enable some foo')
  .option('-b, --bar', 'enable some bar')
  .option('-B, --baz', 'enable some baz');

program.on('--foo', function(){
  console.log('Stuff!');
});

1
这不是我正在寻找的。我正在寻找一个节点框架,可以帮助我编写shell脚本。例如:我有这个用bash编写的脚本https://github.com/gdbtek/setup-graphite/blob/master/ubuntu.bash,我想在node中实现它。如果使用Node.js太麻烦,我认为在bash脚本中完成会更好。 - Nam Nguyen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接