2014-01-30 101 views
1

我有这个程序(用C编写的btw ...),我想从我的nodejs服务器中调用它。 我想传递一个字符串到它的stdin,同时重定向/管道它的stdout到一个文件。从nodejs中执行文件,将stdin和管道stdout写入文件

我知道process_child有一些方法来实现这一行为,所以我尝试:

program = child_process.execFile('program'); 
fileStream = fs.createWriteStream('file.txt'); 
program.stdout.pipe(fileStream);  
program.stdin.end('hello world!'); 

此行program.stdin.end("...")抛出一些错误。

应该是这样echo "hellow world!" | ./program > file.txt

//$ cat program.c 
#include <stdio.h> 

int main() { 
    char aux[100]; 

    scanf("%s", aux); 
    printf("[%s]", aux); 

    return 0; 
} 

更新:

使用'./program'代替'program'问题的解决一部分。

更新2

使用'hellow world!\r\n',或file.txt的只会是空的。 但我的程序不读\ n,它使用%s读取。 据我所知,它会读直到\ n或EOF。 例如,echo -n "mimimi" | ./test作品(在无标准输入\ n)的

+0

它是否可以用'child_process.spawn('echo')' – Plato

回答

2

这是为我工作...

我使用的测试脚本(名为通量)为:

#!/bin/bash 

while read x ; do echo $x ; done 

而且代码需要linebreaks

var child_process = require('child_process'); 
var fs = require('fs'); 

program = child_process.execFile('./flux'); 
fileStream = fs.createWriteStream('file.txt'); 
program.stdout.pipe(fileStream); 
program.stdin.end("hello world!\r\n"); 
+1

f ***我的生活。我会再次测试并更新我的问题,如果错误。感谢:) – Josmar

+0

更新我的代码中有问题的问题。 – Josmar

+0

没有'/ r/n',file.txt将是空的。为什么? – Josmar