Skip to content

Commit 054db41

Browse files
committed
Refactor cat tool: simplify line handling and improve output formatting
1 parent 9f4f7aa commit 054db41

1 file changed

Lines changed: 5 additions & 12 deletions

File tree

  • implement-shell-tools/cat

implement-shell-tools/cat/cat.js

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#!/usr/bin/env node
22

33
const fs = require('fs');
4+
const path = require('path');
45

56
function cat(files, options) {
67
let lineNumber = 1;
@@ -9,23 +10,15 @@ function cat(files, options) {
910
try {
1011
const data = fs.readFileSync(file, 'utf8');
1112
const lines = data.split('\n');
12-
const hasTrailingNewline = data.endsWith('\n');
13-
14-
lines.forEach((line, index) => {
15-
const isVirtualTrailingLine = hasTrailingNewline && index === lines.length - 1;
16-
if (isVirtualTrailingLine) {
17-
return;
18-
}
1913

14+
lines.forEach((line) => {
2015
let prefix = '';
21-
const shouldNumberLine = options.numberLines || (options.numberNonEmpty && line.length > 0);
16+
const shouldNumberLine = options.numberLines || (options.numberNonEmpty && line.trim());
2217
if (shouldNumberLine) {
23-
prefix = `${String(lineNumber).padStart(6)}\t`;
18+
prefix = `${lineNumber}\t`;
2419
lineNumber++;
2520
}
26-
27-
const shouldAppendNewline = hasTrailingNewline || index < lines.length - 1;
28-
process.stdout.write(`${prefix}${line}${shouldAppendNewline ? '\n' : ''}`);
21+
console.log(`${prefix}${line}`);
2922
});
3023
} catch (err) {
3124
if (err.code === 'ENOENT') {

0 commit comments

Comments
 (0)