import fs from "fs/promises"; import { pipeline } ...

Criado em: 9 de maio de 2026

Respondido usando GPT-5.5 Thinking por Chat01

Pergunta

import fs from "fs/promises";
import { pipeline } from "stream/promises";
import path from "path";
process.stdin.on("data", (buff) => {
process.stdout.write(buff);
});
if (process.argv.length > 2) {
for (let index = 2; index < process.argv.length; index++) {
let userGivenPath = process.argv[index];
if (!path.isAbsolute(userGivenPath)) {
userGivenPath = path.join(import.meta.dirname, userGivenPath);
}

text
const fd = await fs.open(userGivenPath, "r"); const readStream = fd.createReadStream(); await pipeline(readStream, process.stdout, { end: true });

}
}
console.log("hi");

Pensamento

undefined

Pensamento

Thought for 13s

Resposta

This looks like a Node.js “echo stdin + cat files” script. A few likely issues:

  1. pipeline(..., process.stdout, { end: true }) is the main bug

    You are piping each file into process.stdout with end: true. That tries to end the writable stream after the first file. Node docs note that streams normally end the destination unless end: false is used, and process.stdout is special but still not something you want pipeline to manage this way. Use end: false. (Node.js)

  2. console.log("hi") may not behave as expected

    Since you are streaming to stdout and then logging afterward, the output will be appended after file contents. Also, if the last file does not end with a newline, you’ll get something like:

    txt
    file contentshi
  3. import.meta.dirname requires modern Node

    import.meta.dirname was added in Node v20.11.0 / v21.2.0 and is no longer experimental in newer Node versions. It only exists for file: modules. (Node.js)

  4. You should close the file handle

    fs.open() gives you a FileHandle. After creating a stream from it, close it when the stream is done, or use fs.createReadStream() from node:fs directly.

A cleaner version:

js
import { createReadStream } from "node:fs"; import { pipeline } from "node:stream/promises"; import path from "node:path"; process.stdin.on("data", (buff) => { process.stdout.write(buff); }); for (let index = 2; index < process.argv.length; index++) { let userGivenPath = process.argv[index]; if (!path.isAbsolute(userGivenPath)) { userGivenPath = path.join(import.meta.dirname, userGivenPath); } await pipeline( createReadStream(userGivenPath), process.stdout, { end: false } ); } process.stdout.write("\nhi\n");

Also consider using process.cwd() instead of import.meta.dirname if you want relative paths to resolve from the directory where the user runs the command, not from the directory containing the script.

Compartilhar esta Q&A