首页 > 解决方案 > 如何将文件通过管道传输到 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)

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

标签: pipedeno

解决方案


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

writeAllfromstd/io将允许将整个子流程Uint8Array写入stdin子流程(如您的评论中所述)。

您还需要关闭stdin子流程(请参阅此问题)。

这是一个完整的例子:

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

推荐阅读