readShebang.js 740 B

123456789101112131415161718192021222324252627282930313233
  1. 'use strict';
  2. const fs = require('fs');
  3. const shebangCommand = require('shebang-command');
  4. function readShebang(command) {
  5. // Read the first 150 bytes from the file
  6. const size = 150;
  7. let buffer;
  8. if (Buffer.alloc) {
  9. // Node.js v4.5+ / v5.10+
  10. buffer = Buffer.alloc(size);
  11. } else {
  12. // Old Node.js API
  13. buffer = new Buffer(size);
  14. buffer.fill(0); // zero-fill
  15. }
  16. let fd;
  17. try {
  18. fd = fs.openSync(command, 'r');
  19. fs.readSync(fd, buffer, 0, size, 0);
  20. fs.closeSync(fd);
  21. } catch (e) { /* Empty */ }
  22. // Attempt to extract shebang (null is returned if not a shebang)
  23. return shebangCommand(buffer.toString());
  24. }
  25. module.exports = readShebang;