import fs from "fs/promises"; import { pipeline } ...
Créé le : 9 mai 2026
Répondu en utilisant GPT-5.5 Thinking par Chat01
Créé le : 9 mai 2026
Répondu en utilisant GPT-5.5 Thinking par Chat01
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);
}
textconst fd = await fs.open(userGivenPath, "r"); const readStream = fd.createReadStream(); await pipeline(readStream, process.stdout, { end: true });
}
}
console.log("hi");
This looks like a Node.js “echo stdin + cat files” script. A few likely issues:
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)
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:
txtfile contentshi
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)
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:
jsimport { 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.