index.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. 'use strict';
  2. const {execFileSync} = require('child_process');
  3. const path = require('path');
  4. const exec = (command, arguments_, shell) => execFileSync(command, arguments_, {encoding: 'utf8', shell}).trim();
  5. const create = (columns, rows) => ({
  6. columns: parseInt(columns, 10),
  7. rows: parseInt(rows, 10)
  8. });
  9. module.exports = () => {
  10. const {env, stdout, stderr} = process;
  11. if (stdout && stdout.columns && stdout.rows) {
  12. return create(stdout.columns, stdout.rows);
  13. }
  14. if (stderr && stderr.columns && stderr.rows) {
  15. return create(stderr.columns, stderr.rows);
  16. }
  17. // These values are static, so not the first choice
  18. if (env.COLUMNS && env.LINES) {
  19. return create(env.COLUMNS, env.LINES);
  20. }
  21. if (process.platform === 'win32') {
  22. try {
  23. // Binary: https://github.com/sindresorhus/win-term-size
  24. const size = exec(path.join(__dirname, 'vendor/windows/term-size.exe')).split(/\r?\n/);
  25. if (size.length === 2) {
  26. return create(size[0], size[1]);
  27. }
  28. } catch (_) {}
  29. } else {
  30. if (process.platform === 'darwin') {
  31. try {
  32. // Binary: https://github.com/sindresorhus/macos-term-size
  33. const size = exec(path.join(__dirname, 'vendor/macos/term-size'), [], true).split(/\r?\n/);
  34. if (size.length === 2) {
  35. return create(size[0], size[1]);
  36. }
  37. } catch (_) {}
  38. }
  39. // `resize` is preferred as it works even when all file descriptors are redirected
  40. // https://linux.die.net/man/1/resize
  41. try {
  42. const size = exec('resize', ['-u']).match(/\d+/g);
  43. if (size.length === 2) {
  44. return create(size[0], size[1]);
  45. }
  46. } catch (_) {}
  47. if (process.env.TERM) {
  48. try {
  49. const columns = exec('tput', ['cols']);
  50. const rows = exec('tput', ['lines']);
  51. if (columns && rows) {
  52. return create(columns, rows);
  53. }
  54. } catch (_) {}
  55. }
  56. }
  57. return create(80, 24);
  58. };