Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell scripting with Node.js

Tags:

node.js

I'm wondering if there are any node framework or node lib out there that I can use to write a shell scripts? For example, I have bash shell program to install Graphite and OpenTSDB RRD tools, I would like to use node.js for it, is it possible?

Thanks

like image 866
Nam Nguyen Avatar asked Oct 17 '13 17:10

Nam Nguyen


People also ask

How do I run a shell script in node js?

Node. js can run shell commands by using the standard child_process module. If we use the exec() function, our command will run and its output will be available to us in a callback. If we use the spawn() module, its output will be available via event listeners.

CAN node js be used for scripting?

Node. js is a toolkit or a platform that allows you to write JavaScript code that runs server-side or even in self-contained applications. Without Node. JS, typically JavaScript code only runs on the client-side in the web browser.

What is shell in 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.

Does node have a shell?

Node. js comes with virtual environment called REPL (aka Node shell). REPL stands for Read-Eval-Print-Loop. It is a quick and easy way to test simple Node.


2 Answers

Take a look at shelljs - it implemets shell and gnu coreutils-like functions. Together with coffeescript it can look very similar to a shell script:

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
like image 179
Andrey Sidorov Avatar answered Sep 23 '22 09:09

Andrey Sidorov


You should check out grunt which is a toolkit for helping people write build and other scripts in node.js. There are a ton of plugins to help you easily do interesting things.

That being said, if you know Bash, I'd just stick with bash.

Check out this interesting thread on Twitter about Bash vs. Grunt scripting

What I Use Grunt For

  • Running Lint Tools
  • Running JS Unit Tests
  • Running Pre-Processors (sass, require.js, uglify, etc.)

What I use Capistrano* For

  • Deploying code to production environments

What I use Bash** for

  • Setting up servers and running them, etc.

  • * capistrano + git or chef or whatever
  • ** bash or whatever other tools you'd want to use
like image 25
Jamund Ferguson Avatar answered Sep 23 '22 09:09

Jamund Ferguson