如何将文件通过管道传输到 Deno 中的子进程中?

How to pipe a file into a sub-process in Deno?

我正在尝试将 SQL 文件的内容通过管道传输到 mysql 进程以在 Deno 中导入转储,如下所示:

const mysql = Deno.run({
    cmd: ["mysql", "--defaults-file=my.cnf", "mydatabase"],
    cwd,
    stdin: "piped"
});

await mysql.stdin.write(
    Deno.readFile("data.sql")
);

await mysql.status();

不幸的是,我得到了错误:

error: Uncaught (in promise) TypeError: Error parsing args: serde_v8 error: ExpectedArray
    await mysql.stdin.write(
                      ^
    at deno:core/core.js:86:46
    at unwrapOpResult (deno:core/core.js:106:13)
    at Object.opAsync (deno:core/core.js:115:28)
    at write (deno:runtime/js/12_io.js:107:23)
    at File.write (deno:runtime/js/40_files.js:84:14)

如何修复错误,以便我能够将我的文件内容提供给子流程?

Deno.readFile returns Promise<Uint8Array>,因此在将其传递给 mysql.stdin.write.

之前,您需要 await

writeAll from std/io will allow for writing the entire Uint8Array to the stdin of a subprocess (as mentioned in ).

您还需要关闭子进程的 stdin(参见 this issue)。

这是一个完整的例子:

piped.ts:

import {writeAll} from 'https://deno.land/std@0.101.0/io/mod.ts';

const filePath = 'hello.txt';

// create example text file
await Deno.writeTextFile(filePath, 'hello world\n');

try {
  // create subprocess
  const subprocess = Deno.run({cmd: ['cat'], stdin: 'piped'});

  // write Uint8Array to stdin
  await writeAll(subprocess.stdin, await Deno.readFile(filePath));

  // close stdin (see https://github.com/denoland/deno/issues/7727)
  subprocess.stdin.close();

  await subprocess.status();
  subprocess.close();
}
finally {
  // remove example text file
  await Deno.remove(filePath);
}
$ deno run --allow-read=hello.txt --allow-run=cat --allow-write=hello.txt piped.ts
hello world