filesystem.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Copyright 2017 Lovell Fuller and others.
  2. // SPDX-License-Identifier: Apache-2.0
  3. 'use strict';
  4. const fs = require('fs');
  5. const LDD_PATH = '/usr/bin/ldd';
  6. const SELF_PATH = '/proc/self/exe';
  7. const MAX_LENGTH = 2048;
  8. /**
  9. * Read the content of a file synchronous
  10. *
  11. * @param {string} path
  12. * @returns {Buffer}
  13. */
  14. const readFileSync = (path) => {
  15. const fd = fs.openSync(path, 'r');
  16. const buffer = Buffer.alloc(MAX_LENGTH);
  17. const bytesRead = fs.readSync(fd, buffer, 0, MAX_LENGTH, 0);
  18. fs.close(fd, () => {});
  19. return buffer.subarray(0, bytesRead);
  20. };
  21. /**
  22. * Read the content of a file
  23. *
  24. * @param {string} path
  25. * @returns {Promise<Buffer>}
  26. */
  27. const readFile = (path) => new Promise((resolve, reject) => {
  28. fs.open(path, 'r', (err, fd) => {
  29. if (err) {
  30. reject(err);
  31. } else {
  32. const buffer = Buffer.alloc(MAX_LENGTH);
  33. fs.read(fd, buffer, 0, MAX_LENGTH, 0, (_, bytesRead) => {
  34. resolve(buffer.subarray(0, bytesRead));
  35. fs.close(fd, () => {});
  36. });
  37. }
  38. });
  39. });
  40. module.exports = {
  41. LDD_PATH,
  42. SELF_PATH,
  43. readFileSync,
  44. readFile
  45. };