【问题标题】:How to pipe a file into a sub-process in Deno?如何将文件通过管道传输到 Deno 的子进程中?
【发布时间】:2021-07-13 16:00:01
【问题描述】:

我正在尝试将 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)

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

【问题讨论】:

    标签: pipe deno


    【解决方案1】:

    Deno.readFile 返回Promise<Uint8Array>,因此您需要先将其传递给await,然后再将其传递给mysql.stdin.write

    writeAll from std/io 将允许将整个Uint8Array 写入子进程的stdin(如your comment 中所述)。

    您还需要关闭子进程的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
    

    【讨论】:

    • 谢谢。 I figured out 这仅适用于小文件。要传递整个文件(没有流式传输),我必须使用 await io.writeAll(subprocess.stdin, await Deno.readFile(filePath));
    • @MartinBraun ? 我更新了示例以使用 writeAll(供未来的读者使用)。
    猜你喜欢
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 2013-06-10
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 2011-06-18
    相关资源
    最近更新 更多