-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
79 lines (69 loc) · 2.25 KB
/
index.js
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
75
76
77
78
79
#! /usr/bin/env node
const path = require('path');
const fs = require('fs');
const moduleName = process.argv[2]
const fnName = process.argv[3]
const params = process.argv.slice(4);
if (!moduleName) {
console.error('File name not provided i.e. run-func ./index.js');
process.exit();
}
if (!fnName) {
console.error('Function name not provided i.e. run-func ./index.js default');
process.exit();
}
const filePath = path.join(process.cwd(), moduleName)
const isLocalFile = path.extname(moduleName) !== ''
try {
if (!isLocalFile && !fs.existsSync(require.resolve(moduleName))) {
console.error('Module is not installed:', moduleName);
process.exit();
}
} catch(e) {
console.error('Module is not installed:', moduleName);
process.exit();
}
if (isES6()) {
import(isLocalFile ? 'file://' + path.resolve(filePath) : moduleName).then((userModule) => {
executeInModule(userModule, fnName, params);
});
} else {
const userModule = require(isLocalFile ? filePath : moduleName);
executeInModule(userModule, fnName, params);
}
async function executeInModule(userMod, fnName, fnParams) {
if (typeof userMod === 'function') {
console.log(await userMod(...fnParams))
return
}
if (!userMod) {
throw new Error(`Module ${userMod} does not exists`);
}
if (!userMod[fnName]) {
throw new Error(`Function ${fnName} is not present or exported from module`);
}
const result = userMod[fnName](...fnParams);
if (typeof result === 'object' && result.then) {
result.then(res => {
typeof res !== 'undefined' && console.log(res);
})
} else if (typeof result !== 'undefined') {
console.log(result);
}
}
function isES6() {
const isLocalFile = path.extname(moduleName) !== ''
const filePath = isLocalFile ? path.join(process.cwd(), moduleName) : require.resolve(moduleName)
let isEs6 = path.extname(moduleName) === '.mjs'
for(var i = 0; i < 10; i ++) {
const dirsAbove = path.join(...new Array(i).fill('..'))
const dir = path.join(path.dirname(filePath), dirsAbove)
const packageJsonPath = path.join(dir, 'package.json')
if (fs.existsSync(packageJsonPath)) {
const packageJson = fs.readFileSync(packageJsonPath)
isEs6 = JSON.parse(packageJson).type === 'module'
break
}
}
return isEs6
}