Skip to content

Commit

Permalink
CLI Piping Investigations
Browse files Browse the repository at this point in the history
Getting insights from GPT into how to construct CLI scripts that can pipe into themselves. I was doing the instancing wrong, I thought they run multiple times, new instances. But they are the same instance, so you use piping and streams so it can work with multiple sets of data coming in over time.

The second disc to Empath for the bonus songs are really great! Didn't quite get them as much before, now I get it having listened about where PowerNerd comes from.

```js
#!/usr/bin/env node
// @  ts-check (edited this because of GitHub)
// echo "hello world!" | ./mycli.js --capitalize | ./mycli.js --lowercase > ./hello_world.txt

// Import necessary modules
import { Transform } from 'node:stream';

// Parse command-line arguments
const args = process.argv.slice(2);
const capitalize = args.includes('--capitalize');
const lowercase = args.includes('--lowercase');

// Detect if stdout is a terminal
if (process.stdout.isTTY) {
  console.error("Error: standard output is a terminal -- ignoring");
  process.exit(1);
}

// Define a transformation function
const transformText = new Transform({
  transform(chunk, encoding, callback) {
    let text = chunk.toString();

    if (capitalize) {
      text = text.toUpperCase();
    }
    if (lowercase) {
      text = text.toLowerCase();
    }

    callback(null, text);
  }
});

// Handle piping in and out
process.stdin.pipe(transformText).pipe(process.stdout);
```

#25
  • Loading branch information
Offroaders123 committed Oct 26, 2024
1 parent b62cfac commit 45ff750
Showing 1 changed file with 5 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/bin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ import { file, nbt, snbt, json, format, space } from "./args.js";

import type { RootTag } from "../index.js";

await main();

async function main(): Promise<void> {
if (file === undefined) {
file satisfies never;
throw new TypeError("Missing argument 'input'");
Expand Down Expand Up @@ -62,4 +65,5 @@ const result: string | Uint8Array = json
: snbt
? `${stringify(output, { space })}\n`
: await write(output);
await stdoutWriteAsync(result);
await stdoutWriteAsync(result);
}

0 comments on commit 45ff750

Please sign in to comment.