簡體   English   中英

從 Deno 運行 bash 腳本

[英]Running bash script from Deno

假設我有這個超級有用和高級的 bash 腳本:

#!/usr/bin/env bash

echo What is your name?
read name
echo What is your age?
read age

當我嘗試使用這樣的簡單腳本從 Deno 運行它時:

const process = Deno.run({
  cmd: [`./bash.sh`],
  stdin: "piped",
  stdout: "piped",
});

const decoder = new TextDecoder();

const output = await process.output()
const parsed = decoder.decode(output);

console.log(parsed);

它什么也不返回,但是如果我將 Deno 腳本簡化為 bash 腳本的第一行,它會返回 output 就好了

const process = Deno.run({
  cmd: [`echo`, `What is your name?`],
  stdin: "piped",
  stdout: "piped",
});

const decoder = new TextDecoder();

const output = await process.output()
const parsed = decoder.decode(output);

console.log(parsed);

為什么是這樣? 我假設自從 bash 文件和單行命令都以 echo 開頭以來,它將返回相同的結果兩次

deno 1.5 版添加了prompt function,它允許您完全消除對不同程序和通過 stdin/stdout 處理進程間通信的需要。

let name: string | null = null;
let age: string | null = null;

while (name === null) {
  name = prompt("What is your name?");
}

while (age === null) {
  age = prompt("What is your age?");
}

console.log(`you are ${name}, ${age}yo`);

您的代碼告訴 Deno 設置子進程以期望管道標准輸入 - 但從未在標准輸入上提供任何內容,因此,它在第一次read時掛起。

如果我們把它拿出來(讓標准輸入從父進程傳遞),並且實際上回答了父進程標准輸入上的兩個提示,一切都會完美運行:

deno run --allow-run run-bash.js <<'EOF'
A Nony Mouse
3
EOF

...使用run-bash.js包含:

const process = Deno.run({
  cmd: [`./bash.sh`],
  stdout: "piped",
});

const decoder = new TextDecoder();

const output = await process.output()
const parsed = decoder.decode(output);

console.log(parsed);

...和您的bash.sh不變。 output因此捕獲兩個提示( What is your name?What is your age? ),並按要求將它們轉發到 javascript 解釋器的標准輸出。

您必須調用bash來調用您的腳本(當然使用--allow-run選項),例如:

const process = Deno.run({
  cmd: ["bash","bash.sh"],
  stdin: "piped",
  stdout: "piped",
});

const decoder = new TextDecoder();

const output = await process.output()
const parsed = decoder.decode(output);

console.log(parsed);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM