已解决通过child_process使用脚本+屏幕

问题描述

解决: 我必须在\r\n添加program.stdin.write(data)(类似program.stdin.write(data+'\r\n')),它才能正常工作。

如果我不输入\r\n,它似乎不会触发,就像在不按Enter的情况下键入一行,因此它将永远不会被处理。

================================================ ==========================

我需要通过child_process访问屏幕,但无法正常工作。 首先,我尝试使用spawn访问。

const {spawn} = require('child_process');
const program = spawn('screen',['-x User/Aplication']);

program.stdout.on('data',data=>{
//Something
})

function writeto(data){
program.stdin.write(data);
}

但是我得到了错误“必须连接到终端错误”。经过一番研究后,我找到了解决方案,使用script + spawn制作一个伪控制台。

const {spawn} = require('child_process');
const program = spawn('script',['/dev/null']);//Pseudo-console
program.stdin.write('screen -x User/Aplication');//I access to screen through the pseudo-console,and it works.

program.stdout.on('data',data=>{
//Something
})

function writeto(data){
program.stdin.write(data);
}

但是...当我尝试使用writeto时,它不起作用。

writeto('Some command here')//Does nothing.

以某种方式,当我通过管道输入控制台时,它可以正常工作!

process.stdin.pipe(program.stdin);

然后,我在控制台中键入内容,它可以正确代理到已连接的screen

问题:使用program.stdin.write时不能正确代理,但是以某种方式,当我通过控制台process.stdin.pipe(program.stdin)

时它可以工作

观察1 :我做了一个简短的echo程序,它与program.stdin.writeprocess.stdin.pipe(program.stdin)一起使用

echo.js

process.stdin.on('data',data=>{
console.log(`[Input]${data}`);
})

main.js

const {spawn} = require('child_process');
const program = spawn('node',['echo.js']);

program.stdout.pipe(process.stdout);

function writeto(data){
program.stdin.write(data);
}

writeto('Test');//Output: [Input]Test
process.stdin.pipe(program.stdin);//I type 'something'. Output: [Input]something

观察2 :使用script + screen并传递控制台内容时,program.stdin.write仅“ buffers”和process.stdin.pipe加载该缓冲区,将其与我输入的内容一起发送。

program.stdin.write('He');//screen receives nothing
program.stdin.write('llo');//screen receives nothing
process.stdin.pipe(program.stdin);//I type ' world!'. screen receives 'Hello World!'

解决方法

这可能不是全部问题,但是spawn的第二个参数应该将每个参数放在单独的数组元素中。

const program = spawn('screen',['-x','User/Aplication']);
,

我必须在\r\n处添加program.stdin.write(data)(类似program.stdin.write(data+'\r\n')),并且有效。

似乎如果我不输入\r\n,它不会作为新行触发,也不会发送它,就像键入all commands in a line without pressing enter so it will never be processed一样。