Skip to content Skip to sidebar Skip to footer

A Way To Call Execl, Execle, Execlp, Execv, Execvp Or Execvp From Node.js

POSIX systems expose family of exec functions, that allow one to load something maybe different into current process, keeping open file descriptors, process identifier and so on. T

Solution 1:

I have created a module to invoke execvp function from NodeJS: https://github.com/OrKoN/native-exec

It works like this:

var exec = require('native-exec');

exec('ls', {
  newEnvKey: newEnvValue,
}, '-lsa'); // => the process is replaced with ls, which runs and exits

Since it's a native node addon it requires a C++ compiler installed. Works fine in Docker, on Mac OS and Linux. Probably, does not work on Windows. Tested with node 6, 7 and 8.

Solution 2:

Solution 3:

Here is an example using node-ffi that works with node v10. (alas, not v12)

#!/usr/bin/node
"use strict";

const ffi = require('ffi');
const ref = require('ref');
constArrayType = require('ref-array');
const stringAry = ArrayType('string');

const readline = require("readline");
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question('Login: ', (username) => {
    username = username.replace(/[^a-z0-9_]/g, "");
    rl.close();
    execvp("/usr/bin/ssh", "-e", "none", username+'@localhost');
});



functionexecvp() {
    var current = ffi.Library(null, 
                              { execvp: ['int', ['string',
                                                 stringAry]],
                                dup2: ['int', ['int', 'int']]});
    current.dup2(process.stdin._handle.fd, 0);
    current.dup2(process.stdout._handle.fd, 1);
    current.dup2(process.stderr._handle.fd, 2);
    var ret = current.execvp(arguments[0], Array.prototype.slice.call(arguments).concat([ref.NULL]));    
}

Post a Comment for "A Way To Call Execl, Execle, Execlp, Execv, Execvp Or Execvp From Node.js"