-
-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathcat.js
More file actions
45 lines (39 loc) · 1.07 KB
/
cat.js
File metadata and controls
45 lines (39 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/usr/bin/env node
// cat.js — basic version (no flags)
import fs from "fs";
const files = process.argv.slice(2);
if (files.length === 0) {
console.error("Usage: node cat.js <file...>");
process.exit(1);
}
let hadError = false;
(async () => {
for (const file of files) {
try {
const stat = await fs.promises.stat(file);
if (stat.isDirectory()) {
console.error(`cat: ${file}: Is a directory`);
hadError = true;
continue;
}
await pipeFile(file);
} catch (err) {
if (err?.code === "ENOENT" || err?.code === "ENOTDIR") {
console.error(`cat: ${file}: No such file or directory`);
} else {
console.error(`cat: ${file}: ${err?.message || "Error"}`);
}
hadError = true;
}
}
if (hadError) process.exitCode = 1;
})();
function pipeFile(file) {
return new Promise((resolve, reject) => {
const rs = fs.createReadStream(file);
rs.on("error", reject);
rs.on("end", resolve);
// important: keep stdout open between files
rs.pipe(process.stdout, { end: false });
});
}