diff --git a/implement-shell-tools/cat/cat.js b/implement-shell-tools/cat/cat.js new file mode 100644 index 000000000..0563a28fa --- /dev/null +++ b/implement-shell-tools/cat/cat.js @@ -0,0 +1,54 @@ +import process from "node:process"; +import { promises as fs } from "node:fs"; + +const args = process.argv.slice(2); + +let option = "none"; +const paths = []; + + +for (const arg of args) { + if (arg === "-n") { + option = "n"; + } else if (arg === "-b") { + option = "b"; + } else { + paths.push(arg); + } +} + +if (paths.length === 0) { + console.error("Expected at least one file path."); + process.exit(1); +} + +for (const path of paths) { + const content = await fs.readFile(path, "utf-8"); + + const lines = content.split("\n"); + + let lineNumber = 1; + + for (const line of lines) { + + if (option === "n") { + console.log(`${lineNumber} ${line}`); + lineNumber++; + } + + else if (option === "b") { + + if (line !== "") { + console.log(`${lineNumber} ${line}`); + lineNumber++; + } else { + console.log(""); + } + + } + + else { + console.log(line); + } + } +} \ No newline at end of file diff --git a/implement-shell-tools/ls/ls.js b/implement-shell-tools/ls/ls.js new file mode 100644 index 000000000..4f8ab1446 --- /dev/null +++ b/implement-shell-tools/ls/ls.js @@ -0,0 +1,29 @@ +import process from "node:process"; +import { promises as fs } from "node:fs"; + +const args = process.argv.slice(2); + +let showAll = false; +let path = "."; + +for (const arg of args) { + + if (arg === "-a") { + showAll = true; + } + + else if (arg !== "-1") { + path = arg; + } +} + +const files = await fs.readdir(path); + +for (const file of files) { + + if (!showAll && file.startsWith(".")) { + continue; + } + + console.log(file); +} \ No newline at end of file diff --git a/implement-shell-tools/wc/wc.js b/implement-shell-tools/wc/wc.js new file mode 100644 index 000000000..72e785240 --- /dev/null +++ b/implement-shell-tools/wc/wc.js @@ -0,0 +1,38 @@ +import process from "node:process"; +import { promises as fs } from "node:fs"; + +const args = process.argv.slice(2); + +let option = "all"; +const paths = []; + +// parse args +for (const arg of args) { + if (arg === "-l") option = "l"; + else if (arg === "-w") option = "w"; + else if (arg === "-c") option = "c"; + else paths.push(arg); +} + +if (paths.length === 0) { + console.error("Please provide at least one file"); + process.exit(1); +} + +for (const path of paths) { + const content = await fs.readFile(path, "utf-8"); + + const lines = content.split("\n").length; + const words = content.split(" ").length; + const chars = content.length; + + if (option === "l") { + console.log(lines, path); + } else if (option === "w") { + console.log(words, path); + } else if (option === "c") { + console.log(chars, path); + } else { + console.log(lines, words, chars, path); + } +} \ No newline at end of file