-
Notifications
You must be signed in to change notification settings - Fork 1
/
execsync.cc
47 lines (36 loc) · 1.05 KB
/
execsync.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <string>
#include <cstdlib>
#include <node.h>
using namespace v8;
Handle<Value> execSync(const Arguments& args)
{
HandleScope scope;
if (!args[0]->IsString()) {
Local<String> msg = String::New("Argument of 'execsync' must be String.");
ThrowException(Exception::TypeError(msg));
return scope.Close(Undefined());
}
const String::Utf8Value utf8_command(args[0]);
const std::string command = std::string(*utf8_command) + " 2>&1";
FILE *fp = popen(command.c_str(), "r");
if (fp == NULL) {
Local<String> msg = String::New("'popen' in 'execsync' failed.");
ThrowException(Exception::TypeError(msg));
return scope.Close(Undefined());
}
const int BUF_SIZE = 1024;
char buf[BUF_SIZE];
std::string result;
while ( fgets(buf, BUF_SIZE, fp) != NULL ) {
result += buf;
}
pclose(fp);
return scope.Close(String::New(result.c_str()));
}
void init(Handle<Object> target) {
target->Set(
String::NewSymbol("execSync"),
FunctionTemplate::New(execSync)->GetFunction()
);
}
NODE_MODULE(shell, init)