Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

London SDC | Samira Hekmati | Module-Tools | Implement-Shell-Tools in JS | Week 3 #53

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
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
35 changes: 35 additions & 0 deletions implement-shell-tools/cat/cat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import fs from "fs/promises"; // Import fs.promises for async file reading
import { Command } from "commander";

const program = new Command();

program
.command("readfiles <files...>") // Accepts multiple file arguments
.description("read text files")
.option("-n, --number", "show line number")
.option("-b, --non-blank", "number 'only' the non-blank lines")
.action(async (files, options) => {
let lineCounter = 1; // Continuous line number for `-n`
let nonBlankCounter = 1; // Non-blank line number for `-b`

for (const file of files) {
try {
// Read file content using promises (async/await)
const data = await fs.readFile(file, "utf8");
let lines = data.split("\n");

if (options.number) {
lines = lines.map((line) => `${lineCounter++} ${line}`);
} else if (options.nonBlank) {
lines = lines.map((line) =>
line.trim() === "" ? line : `${nonBlankCounter++} ${line}`
);
}
console.log(lines.join("\n"));
} catch (err) {
console.error(err);
}
}
});

program.parse();
24 changes: 24 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": "re-implementing shell tools like cat using Node.js",
"main": "cat.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Samira",
"license": "ISC",
"dependencies": {
"commander": "^13.1.0"
}
}
44 changes: 44 additions & 0 deletions implement-shell-tools/ls/ls.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
//note to myself:
// path.resolve() converts a relative path into an absolute path.
//The last argument (dir) is resolved relative to the first argument.
//syntax: path.resolve(...paths);
//process.cwd() Returns the current working directory of the process (i.e., where the user ran the command from).It does NOT return the script’s directory.
//targetDir is created to store this resolved absolute path for reliable use in fs.readdirSync().
import fs from "fs/promises";
import { Command } from "commander";
import path from "path";

const program = new Command();

program
.argument('[directory]', 'Directory to list', '.')//This specifies the directory argument. If no directory is provided, it defaults to the current directory (.)
.option("-l, --format", "List files in a single column") // Add -1 flag
.option("-a, --hidden", "Show hidden files (like ls -a)") // Add -a flag
.action(async (directory) => {
const resolvedPath = path.resolve(directory);

const options = program.opts();

try {
const files = await fs.readdir(resolvedPath, { withFileTypes: true }); // files is an array of files inside the directory
//{ withFileTypes: true } returns file objects, allowing you to filter out hidden files if needed.


// If `-a` is NOT set, filter out hidden files (those starting with ".")
let filteredFiles = files.map(file => file.name);

if(!options.hidden){
filteredFiles = filteredFiles.filter(file => !file.startsWith("."));
}
if(options.format){
console.log(filteredFiles.join("\n"))// Print files in a single column (default `ls -1` behavior)
}else{
console.log(filteredFiles.join(" "))// Print files space-separated (default `ls` behavior)
}
} catch (error) {
console.error(`Error reading directory: ${error.message}`);
process.exit(1);
}
})

program.parse(process.argv);
24 changes: 24 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": "\"writing ls implementation\"",
"main": "ls.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Samira",
"license": "ISC",
"dependencies": {
"commander": "^13.1.0"
}
}
24 changes: 24 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": "build a custom version of the wc with nodeJs",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Samira",
"license": "ISC",
"dependencies": {
"commander": "^13.1.0"
}
}
52 changes: 52 additions & 0 deletions implement-shell-tools/wc/wc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import fs from "fs/promises";
import { Command } from "commander";

const program = new Command(); //Creates a new instance of the Command class, which will handle our command-line arguments and commands.

// Write a function to count lines, words and bytes

async function count(file, options) {
const data = await fs.readFile(file, "utf8");

const linesCount = data.split("\n").length;

const wordsCount = data.split(/\s+/).filter(Boolean).length;

const bytes = Buffer.byteLength(data, "utf8");

let output = `${file}:`; //creates a string variable that will be used to store and build the final string that will be printed to the console.

if (options.lines) {
output += ` ${linesCount}`;
console.log(output);
}
if (options.words) {
output += ` ${wordsCount}`;
console.log(output);
}

if (options.bytes) {
output += `${bytes}`;
console.log(output);
}

// If no options were provided, show all counts
if (!options.lines && !options.words && !options.bytes) {
output += ` ${linesCount} ${wordsCount} ${bytes}`;
console.log(output);
}
}

program
.command("wc <files...>") //The <files...> syntax means it accepts one or more file names as arguments.
.description("Count lines, words, and bytes in text files")
.option("-l, --lines", "Count lines")
.option("-w, --words", "Count words")
.option("-c, --bytes", "Count bytes")
.action(async (files, options) => {
for (const file of files) {
await count(file, options);
}
});

program.parse();