JavaScript - find all available functions and properties in an object
The following three functions are very useful on inspecting methods and properties in any Javascrip object.
Github code: https://github.com/nsclass/describe-javascript-object-methods/blob/master/list-object-methods.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
const getArgs = func => {
// First match everything inside the function argument parens.
let matchedItems = func.toString().match(/function\s.*?\(([^)]*)\)/)
if (matchedItems && matchedItems.length > 0) {
let args = matchedItems[1].trim()
if (args.length > 0) {
// Split the arguments string into an array comma delimited.
return args.split(',').map( arg => {
// Ensure no inline comments are parsed and trim the whitespace.
return arg.replace(/\/\*.*\*\//, '').trim()
})
}
}
return "no args"
}
const getMethods = (obj) => {
return Object.entries(obj)
.filter(([key, value]) => typeof obj[key] === 'function')
.map(([key, value]) => `${key}: ${getArgs(value)}`)
.sort((x, y) => {
let strX = x.toString()
let strY = y.toString()
return strX.localeCompare(strY)
})
}
const getProperties = obj => {
return Object.getOwnPropertyNames(obj)
.filter(item => typeof obj[item] !== 'function')
}
For instance, we can list all available functions and each function's arguemnts in fs node module.
1
2
const fs = require('fs)
getMethods(fs)
Results
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
[ '_debugEnd: no args',
'_debugProcess: no args',
'_fatalException: no args',
'_getActiveHandles: no args',
'_getActiveRequests: no args',
'_kill: no args',
'_linkedBinding: module',
'_rawDebug: no args',
'_startProfilerIdleNotifier: no args',
'_stopProfilerIdleNotifier: no args',
'_tickCallback: no args',
'abort: no args',
'activateUvLoop: no args',
'assert: ...args',
'atomBinding: name',
'binding: module',
'chdir: ...args',
'cpuUsage: prevValue',
'crash: no args',
'cwd: no args',
'dlopen: no args',
'emitWarning: no args',
'exit: no args',
'getCPUUsage: no args',
'getCreationTime: no args',
'getegid: no args',
'geteuid: no args',
'getgid: no args',
'getgroups: no args',
'getHeapStatistics: no args',
'getIOCounters: no args',
'getRenderProcessPreferences: no args',
'getSystemMemoryInfo: no args',
'getuid: no args',
'hang: no args',
'hasUncaughtExceptionCaptureCallback: no args',
'hrtime: time',
'initgroups: ...args',
'kill: no args',
'log: no args',
'memoryUsage: no args',
'NativeModule: id',
'nextTick: no args',
'openStdin: no args',
'reallyExit: no args',
'setegid: ...args',
'seteuid: ...args',
'setFdLimit: no args',
'setgid: ...args',
'setgroups: ...args',
'setuid: ...args',
'setUncaughtExceptionCaptureCallback: no args',
'takeHeapSnapshot: no args',
'umask: ...args',
'uptime: no args' ]