cat.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. var common = require('./common');
  2. var fs = require('fs');
  3. common.register('cat', _cat, {
  4. canReceivePipe: true,
  5. cmdOptions: {
  6. 'n': 'number',
  7. },
  8. });
  9. //@
  10. //@ ### cat([options,] file [, file ...])
  11. //@ ### cat([options,] file_array)
  12. //@
  13. //@ Available options:
  14. //@
  15. //@ + `-n`: number all output lines
  16. //@
  17. //@ Examples:
  18. //@
  19. //@ ```javascript
  20. //@ var str = cat('file*.txt');
  21. //@ var str = cat('file1', 'file2');
  22. //@ var str = cat(['file1', 'file2']); // same as above
  23. //@ ```
  24. //@
  25. //@ Returns a string containing the given file, or a concatenated string
  26. //@ containing the files if more than one file is given (a new line character is
  27. //@ introduced between each file).
  28. function _cat(options, files) {
  29. var cat = common.readFromPipe();
  30. if (!files && !cat) common.error('no paths given');
  31. files = [].slice.call(arguments, 1);
  32. files.forEach(function (file) {
  33. if (!fs.existsSync(file)) {
  34. common.error('no such file or directory: ' + file);
  35. } else if (common.statFollowLinks(file).isDirectory()) {
  36. common.error(file + ': Is a directory');
  37. }
  38. cat += fs.readFileSync(file, 'utf8');
  39. });
  40. if (options.number) {
  41. cat = addNumbers(cat);
  42. }
  43. return cat;
  44. }
  45. module.exports = _cat;
  46. function addNumbers(cat) {
  47. var lines = cat.split('\n');
  48. var lastLine = lines.pop();
  49. lines = lines.map(function (line, i) {
  50. return numberedLine(i + 1, line);
  51. });
  52. if (lastLine.length) {
  53. lastLine = numberedLine(lines.length + 1, lastLine);
  54. }
  55. lines.push(lastLine);
  56. return lines.join('\n');
  57. }
  58. function numberedLine(n, line) {
  59. // GNU cat use six pad start number + tab. See http://lingrok.org/xref/coreutils/src/cat.c#57
  60. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
  61. var number = (' ' + n).slice(-6) + '\t';
  62. return number + line;
  63. }