Skip to content

Instantly share code, notes, and snippets.

@shalomsam
Created November 10, 2021 01:46
Show Gist options
  • Select an option

  • Save shalomsam/77154c3f9925f53e66e76354bfd7e9f7 to your computer and use it in GitHub Desktop.

Select an option

Save shalomsam/77154c3f9925f53e66e76354bfd7e9f7 to your computer and use it in GitHub Desktop.
Shell Tail command in Node.js
#!/usr/bin/env node
let fs = require('fs');
let path = require('path');
let args = process.argv.slice(2);
//console.log(args);
let parseArgs = (args) => {
let parsed = {};
let maxlen = 2;
let argsStr = args.join(' ');
let file = argsStr.match(/-(-)?f(ile)?(=|[\s])"?(?<file>\S+)"?/);
if (file && file.groups && file.groups.file) {
file = file.groups.file;
}
if (!file) {
throw new Error('Argument --file(-f) is required!');
}
let lines = argsStr.match(/-(-)?l(ines)?(=|[\s])"?(?<lines>\S+)"?/);
if (lines && lines.groups && lines.groups.lines) {
lines = Number(lines.groups.lines);
} else {
lines = 10;
}
return {
file: file.trim(),
lines
}
}
let file, lines;
try {
let parsed = parseArgs(args);
file = parsed.file;
lines = parsed.lines;
} catch (e) {
console.log(e.message);
return 0;
}
//console.log('file >> ', file);
//console.log('lines >> ', lines);
fs.readFile(path.join(__dirname,file), (err, data) => {
if (err) {
console.log('Error:' + err.message);
return 0;
}
//console.log('Data: > ', data);
let out = data.toString().split("\n").slice(-(lines + 1)).join("\n");
console.log(out);
return 1;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment