UNPKG

1.76 kBJavaScriptView Raw
1const fs = require('fs');
2const {versionGteLt} = require('../dist/util');
3
4// In node's core, this is implemented in C
5// https://github.com/nodejs/node/blob/v15.3.0/src/node_file.cc#L891-L985
6/**
7 * @param {string} path
8 * @returns {[] | [string, boolean]}
9 */
10function internalModuleReadJSON(path) {
11 let string
12 try {
13 string = fs.readFileSync(path, 'utf8')
14 } catch (e) {
15 if (e.code === 'ENOENT') return []
16 throw e
17 }
18 // Node's implementation checks for the presence of relevant keys: main, name, type, exports, imports
19 // Node does this for performance to skip unnecessary parsing.
20 // This would slow us down and, based on our usage, we can skip it.
21 const containsKeys = true
22 return [string, containsKeys]
23}
24
25// In node's core, this is implemented in C
26// https://github.com/nodejs/node/blob/63e7dc1e5c71b70c80ed9eda230991edb00811e2/src/node_file.cc#L987-L1005
27/**
28 * @param {string} path
29 * @returns {number} 0 = file, 1 = dir, negative = error
30 */
31function internalModuleStat(path) {
32 const stat = fs.statSync(path, { throwIfNoEntry: false });
33 if(!stat) return -1;
34 if(stat.isFile()) return 0;
35 if(stat.isDirectory()) return 1;
36}
37
38/**
39 * @param {string} path
40 * @returns {number} 0 = file, 1 = dir, negative = error
41 */
42function internalModuleStatInefficient(path) {
43 try {
44 const stat = fs.statSync(path);
45 if(stat.isFile()) return 0;
46 if(stat.isDirectory()) return 1;
47 } catch(e) {
48 return -e.errno || -1;
49 }
50}
51
52const statSupportsThrowIfNoEntry = versionGteLt(process.versions.node, '15.3.0') ||
53 versionGteLt(process.versions.node, '14.17.0', '15.0.0');
54
55module.exports = {
56 internalModuleReadJSON,
57 internalModuleStat: statSupportsThrowIfNoEntry ? internalModuleStat : internalModuleStatInefficient
58};