read-package.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. // This is JUST the code needed to open a package.json file and parse it.
  2. // It's isolated out so that code needing to parse a package.json file can do so in the same way as this module does, without needing to require the whole module, or needing to require the underlying parsing library.
  3. const { readFile } = require('fs/promises')
  4. const parseJSON = require('json-parse-even-better-errors')
  5. async function read (filename) {
  6. try {
  7. const data = await readFile(filename, 'utf8')
  8. return data
  9. } catch (err) {
  10. err.message = `Could not read package.json: ${err}`
  11. throw err
  12. }
  13. }
  14. function parse (data) {
  15. try {
  16. const content = parseJSON(data)
  17. return content
  18. } catch (err) {
  19. err.message = `Invalid package.json: ${err}`
  20. throw err
  21. }
  22. }
  23. // This is what most external libs will use.
  24. // PackageJson will call read and parse separately
  25. async function readPackage (filename) {
  26. const data = await read(filename)
  27. const content = parse(data)
  28. return content
  29. }
  30. module.exports = {
  31. read,
  32. parse,
  33. readPackage,
  34. }