-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode-fetch-patch.js
More file actions
74 lines (73 loc) · 2.78 KB
/
node-fetch-patch.js
File metadata and controls
74 lines (73 loc) · 2.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
let exported = {};
let patchType = null
process.env.PATCHTYPE = null;
global.patchType = null;
if(typeof global.fetch === "function"){
// checking if the native fetch api is supported, if yes exporting it.
//if this throws an error:
// nodejs api's fetch function is not available.
// trying node-fetch
global.fetch.patchType = 0;
exported = global.fetch;
patchType = 0;
process.env.PATCHTYPE = 0;
global.patchType = 0;
}
else{
// nodejs native fetch api not found, trying to use node-fetch
try{
require.resolve("node-fetch");
const nodeFetch2 = require("node-fetch")
exported = nodeFetch2
// checking for node-fetch@=<2.6.1, if found exporting it.
// if this throws an error:
// commonJS require for node-fetch is not available, so node-fetch doesn't exist or its version is higher than 2.6.1
// trying to import node-fetch using commonJS import
patchType = 2;
process.env.PATCHTYPE = 2;
global.patchType = 2;
}
catch(err){
try{
require.resolve("node-fetch")
const nodeFetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));
exported = nodeFetch;
// if this throws an error:
// any version of node-fetch or native fetch api is not available
// trying to install node-fetch with node package manager
patchType = 3;
process.env.PATCHTYPE = 3;
global.patchType = 3;
}
catch(error){
// using npm to install node-fetch
patchType = undefined;
delete process.env.PATCHTYPE;
global.patchType = undefined;
require("child_process").exec("npm install node-fetch", (err, stdout, stderr) => {
if(err) console.error(err)
if(stderr) console.log(stderr)
if(stdout) console.log(stdout)
if(!require.main){
require("child_process").spawn(process.execPath, [],{
cwd: process.cwd (),
detached: true,
stdio: 'inherit'
});
console.log("[node-fetch-patch] restarting node console")
}
else{
require("child_process").spawn(process.execPath, [require.main.filename],{
cwd: process.cwd (),
detached: true,
stdio: 'inherit'
});
console.log("[node-fetch-patch] restarting " + require.main.filename)
}
})
}
}
}
// exporting the found fetch method
module.exports = exported
module.exports.patchType = patchType