codekingpro/portable-devtools
114k
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
4const { readFile } = require('fs/promises')
5const parseJSON = require('json-parse-even-better-errors')
6
7async function read (filename) {
8 try {
9 const data = await readFile(filename, 'utf8')
10 return data
11 } catch (err) {
12 err.message = `Could not read package.json: ${err}`
13 throw err
14 }
15}
16
17function parse (data) {
18 try {
19 const content = parseJSON(data)
20 return content
21 } catch (err) {
22 err.message = `Invalid package.json: ${err}`
23 throw err
24 }
25}
26
27// This is what most external libs will use.
28// PackageJson will call read and parse separately
29async function readPackage (filename) {
30 const data = await read(filename)
31 const content = parse(data)
32 return content
33}
34
35module.exports = {
36 read,
37 parse,
38 readPackage,
39}
40 