鉴于我有一个name.js
脚本,其中有两个提示,如下所示:
What is your first name? Foo
What is your surname? Bar
Hello Foo Bar.
我将如何使用child_process.spawn()
发送两个输入,以便脚本正确地打印名字和姓氏?
我尝试使用[process].write(Foo); [process].end();
,但是这导致流被关闭,无法接受该姓氏。
以下是name.js
的代码。它使用prompts npm软件包。
const prompts = require('prompts');
prompts({
type: 'text',
name: 'firstName',
message: 'What is your first name?',
})
.then(response => {
prompts({
type: 'text',
name: 'surname',
message: 'What is your surname?',
})
.then(secondResponse => {
console.log(`Hello ${response.firstName} ${secondResponse.surname}.`);
});
});
以下是我尝试使此功能正常运行的一些方法,但无济于事。
const {spawn} = require('child_process');
const sampleOne = spawn('name.js');
sampleOne.stdin.write('Foo\nBar');
sampleOne.stdin.end(); // This method results in 'First name' being 'FooBar'.
const sampleTwo = spawn('name.js');
sampleTwo.stdin.write('Foo');
sampleTwo.stdin.end();
sampleTwo.stdin.write('Bar');
sampleTwo.stdin.end(); // Correctly writes 'Foo' as 'First name' but cannot write 'surname' as stdin steam is closed.
答案 0 :(得分:0)
如果您要继续向子进程发送数据,则不应将标准输入流close
子进程。它应该是连续的流。如果您想知道如何向流程发送多个输入,则可能必须使用在第一个方案中实现的输入分隔符,例如sampleOne.stdin.write('Foo\nBar\n');
并在子脚本中进行处理。
考虑到用户手动遵循此过程,What is your first name?
会显示在控制台上(因此写入了过程中的stdout
)。用户键入Foo
,然后输入(\n
)。因此输入将为Foo\n
,并且stdin流不会关闭stdin。然后What is your surname?
打印到终端中,然后用户输入Bar
,然后按Enter(\n
),因此输入将为Bar\n
因此,总流输入为Foo\nBar\n
,如果这不起作用,请尝试等到第二个输出打印到控制台后再发送Bar\n
。