Node.js Exec Like Ruby Exec and Writing a Node.js Native Add On Module

Recently, I was faced with a problem that required my Node.js programs process to execute another process and have the procoess that's passed to the exec function completely replace the Node.js process. In short, I wanted an 'exec' function like Ruby's 'exec' function. Unfortunately, out of the box, Node.js doesn't support this functionality. I asked on Stackoverflow.com, and someone had a response that I should use the POSIX exec functions to solve my problem and to consider writing a native Node.js extension.

npm install kexec

You can then use it like:

var kexec = require('kexec');
kexec('top'); //you can pass any process that you want here

Here is the C++ source for Node Kexec:

#include <v8.h>
#include <node.h>
#include <cstdio>

//#ifdef __POSIX__
#include <unistd.h>
/*#else
#include <process.h>
#endif*/

using namespace node;
using namespace v8;

static Handle<Value> kexec(const Arguments& args) {
    String::Utf8Value v8str(args[0]);
    char* argv2[] = {"", "-c", *v8str, NULL};

    execvp("/bin/sh", argv2);      
    return Undefined();
}

extern "C" {
    static void init (Handle<Object> target) {
        NODE_SET_METHOD(target, "kexec", kexec);
    }

    NODE_MODULE(kexec, init);
}

As you can see, writing a C++ add on in Node.js isn't too difficult. You can use it in your Node.js Javascript like so:

var kexec;

try {
  kexec = require("./build/default/kexec.node"); //Node.js v0.4
} catch(e) {
  kexec = require("./build/Release/kexec.node"); //Node.js v0.6
}

module.exports = kexec.kexec; //function of kexec module is named kexec

Don't forget your wscript file, which ironically is Python code:

def set_options(opt):
  opt.tool_options("compiler_cxx")

def configure(conf):
  conf.check_tool("compiler_cxx")
  conf.check_tool("node_addon")

def build(bld):
  obj = bld.new_task_gen("cxx", "shlib", "node_addon") 
  obj.cxxflags = ["-g", "-D_FILE_OFFSET_BITS=64", "-D_LARGEFILE_SOURCE","-Wall"]
  obj.target = "kexec"
  obj.source = "src/node_kexec.cpp"

In your package.json, include this bit:

"scripts": { "install": "node-waf configure build" }

Github Sourcecode: Node.js kernel exec

I've also included other resources for writing a Node.js Native Add On Module:

  1. Google V8 Engine Getting Started
  2. Google V8 Embedder's Guide
  3. How to Roll Your Own Javascript API with V8
  4. How to Write Your Own Native Node.js Extension
  5. Writing Node.js Native Extensions
  6. Node.js Native Extension with Hammer and a Prayer
  7. Mastering Node; Add Ons
  8. Node.js Documentation: Add Ons
  9. Postgres Node.js Module
  10. V8 Sample: shell.cc
  11. V8 Objects
  12. There's C in My JavaScript
  13. Converting V8 Arguments to C++ Types

If you made it this far, you should follow me on Twitter.

-JP

Want to test-drive Bitcoin without any risk? Check out my bitcoin wallet Coinbolt. It includes test coins for free.

comments powered by Disqus