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:
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