Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions implement-shell-tools/cat/cat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { program } from "commander";
import { promises as fs } from "node:fs";

program
.argument("<files...>", "List of files to concatenate")
.name("cat")
.description("Concatenate FILE(s) to standard output.")
.option("-n", "Number all input lines")
.option("-b", "Number non-blank input lines");

program.parse();

const files = program.args;
const { n, b } = program.opts();

async function main() {
let catAllData = "";

for (const file of files) {
const data = await fs.readFile(file, "utf8");
catAllData += data;
Comment on lines +19 to +21

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How much input must remain in memory before the first write when cat receives a large file?

To "like" or "dislike" this comment, please follow this link

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All of it. Nothing is written until line 35. So peak memory is the total size of all input files, no matter how large the files are. I believe this is not that good, memory wise.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From what I've researched, cat is using streaming. Should I try to implement that, or is this solution ok?

}

const endsWithNewline = catAllData.endsWith("\n");
let dataArray = catAllData === "" ? [] : catAllData.split("\n");

// A trailing newline produces a final empty element in the split array.
// Drop it so it isn't numbered as a phantom line; the newline is restored
// when the lines are joined back together.
if (endsWithNewline) {
dataArray.pop();
}

if (b) {
let lineNumber = 1;
dataArray = dataArray.map((line) =>
line ? `${lineNumber++}\t${line}` : line,
);
} else if (n) {
dataArray = dataArray.map((line, index) => `${index + 1}\t${line}`);
Comment thread
tomdu3 marked this conversation as resolved.
Resolved
}

process.stdout.write(
dataArray.join("\n") + (endsWithNewline ? "\n" : ""),
);
}

main().catch((err) => {
console.error(err);
process.exit(1);
});
25 changes: 25 additions & 0 deletions implement-shell-tools/cat/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions implement-shell-tools/cat/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "cat",
"version": "1.0.0",
"description": "JS implementation of the `cat` command line tool.",
"license": "ISC",
"author": "",
"type": "module",
"main": "cat.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"commander": "^15.1.0"
}
}
71 changes: 71 additions & 0 deletions implement-shell-tools/ls/ls.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { program } from "commander";
import { promises as fs } from "node:fs";

program
.argument("[paths...]", "Paths to list files.", ["."])
.name("ls")
.description(
"List information about the FILEs (the current directory by default).",
)
.option("-1, --one", "List one file per line")
.option("-a, --all", "Do not ignore entries starting with .");

program.parse();

const paths = program.args.length ? program.args : ["."];
const { one, all } = program.opts();

const sortNames = (a, b) =>
a.localeCompare(b, undefined, { ignorePunctuation: true });

async function main() {
const files = [];
const dirs = [];

for (const p of paths) {
const stats = await fs.stat(p);
if (stats.isDirectory()) {
dirs.push(p);
} else {
files.push(p);
}
}

files.sort(sortNames);
dirs.sort(sortNames);

const sep = one ? "\n" : " ";

if (files.length > 0) {
console.log(files.join(sep));
}

for (let i = 0; i < dirs.length; i++) {
const dir = dirs[i];

if (files.length > 0 || i > 0) {
console.log();
}

if (paths.length > 1) {
console.log(`${dir}:`);
}

let fileNames = await fs.readdir(dir);
if (all) {
fileNames.unshift(".", "..");
} else {
fileNames = fileNames.filter((name) => !name.startsWith("."));
}
fileNames.sort(sortNames);

if (fileNames.length > 0) {
console.log(fileNames.join(sep));
}
}
}

main().catch((err) => {
console.error(err);
process.exit(1);
});
25 changes: 25 additions & 0 deletions implement-shell-tools/ls/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions implement-shell-tools/ls/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "ls",
"version": "1.0.0",
"description": "Implementation of the `ls` shell command",
"license": "ISC",
"author": "",
"type": "module",
"main": "ls.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"commander": "^15.1.0"
}
}
25 changes: 25 additions & 0 deletions implement-shell-tools/wc/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions implement-shell-tools/wc/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "wc",
"version": "1.0.0",
"description": "Implementation of the `wc` tool in NodeJS",
"license": "ISC",
"author": "",
"type": "module",
"main": "wc.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"commander": "^15.1.0"
}
}
76 changes: 76 additions & 0 deletions implement-shell-tools/wc/wc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { program } from "commander";
import { promises as fs } from "node:fs";

program
.argument("<files...>", "Files to count")
.name("wc")
.description("Print newline, word, and byte counts for each FILE.")
.option("-l, --lines", "Print the newline counts")
.option("-w, --words", "Print the word counts")
.option("-c, --bytes", "Print the byte counts");

program.parse();

const files = program.args;
const opts = program.opts();

const noFlags = !opts.lines && !opts.words && !opts.bytes;
const showLines = noFlags || Boolean(opts.lines);
const showWords = noFlags || Boolean(opts.words);
const showBytes = noFlags || Boolean(opts.bytes);

function countBuffer(buffer) {
let lines = 0;
for (const byte of buffer) {
if (byte === 0x0a) lines++;
}

const text = buffer.toString("utf8").trim();
const words = text ? text.split(/\s+/).length : 0;
const bytes = buffer.length;

return { lines, words, bytes };
}

function formatRow(counts, name, width) {
const cols = [];
if (showLines) cols.push(String(counts.lines).padStart(width, " "));
if (showWords) cols.push(String(counts.words).padStart(width, " "));
if (showBytes) cols.push(String(counts.bytes).padStart(width, " "));
cols.push(name);
return cols.join(" ");
}

async function main() {
const results = [];
const total = { lines: 0, words: 0, bytes: 0 };

for (const file of files) {
const buffer = await fs.readFile(file);
const counts = countBuffer(buffer);
results.push({ name: file, ...counts });
total.lines += counts.lines;
total.words += counts.words;
total.bytes += counts.bytes;
}

const columnCount =
Number(showLines) + Number(showWords) + Number(showBytes);
const width =
results.length === 1 && columnCount === 1
? 1
: String(total.bytes).length;

for (const result of results) {
console.log(formatRow(result, result.name, width));
}

if (results.length > 1) {
console.log(formatRow(total, "total", width));
}
}

main().catch((err) => {
console.error(err);
process.exit(1);
});
Loading