【问题标题】:Using script + screen through child_process通过 child_process 使用脚本 + 屏幕
【发布时间】:2020-08-13 01:19:05
【问题描述】:

已解决: 我必须在program.stdin.write(data) 处添加\r\n(类似于program.stdin.write(data+'\r\n'))并且它起作用了。

看来如果我不输入\r\n,它不会触发,就像输入一行而不按回车,所以它永远不会被处理。

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

我需要通过 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,它适用于 program.stdin.writeprocess.stdin.pipe(program.stdin)

echo.js

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

ma​​in.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 仅“缓冲区”和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!'

【问题讨论】:

    标签: node.js bash pipe child-process


    【解决方案1】:

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

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

    【讨论】:

    • 我解决了,我不得不在program.stdin.write(data) 处添加“\r\n”,没有它就像只输入一行而不按回车,我的程序不能那样工作。这就是为什么它“缓冲”并且仅在管道时发送的原因,因为我的控制台在末尾添加了“\r\n”。
    【解决方案2】:

    我必须在program.stdin.write(data) 处添加\r\n(类似于program.stdin.write(data+'\r\n')),它起作用了。

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

    【讨论】:

      猜你喜欢
      • 2021-01-05
      • 2010-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多