Home > front end >  Get javascript object types as console.log outputs in node.js
Get javascript object types as console.log outputs in node.js

Time:02-12

I need to introspect some objects to know their type. In particular, I need to identify functions and async functions. For example consider the following object:

f = function(){}
af = async function(){}
class c {}

Using typeof won't work because for any of these objects, the type is function


> typeof f
'function'
> typeof af
'function'
> typeof c
'function'

This improves a little if I use Object.prototype.toString.call() on each object:

> Object.prototype.toString.call(f)
'[object Function]'
>Object.prototype.toString.call(af)
'[object AsyncFunction]'
>Object.prototype.toString.call(c)
'[object Function]'

I still, cannot differentiate a function from a class. However, console.log is able to do it:

> console.log(f)
[Function: f]
> console.log(af)
[AsyncFunction: af]
> console.log(c)
[class c]

So my question is, how can I mimic what console.log is doing to identify the correct type of a class?

CodePudding user response:

Use the util module of Node.js, for instance the inspect function.

Note: You need to import it const util = require("util"). It's not a global object!

> class A {}
> util.inspect(A)
'[class A]'
> f = () => {}
> af = async () => {}
> util.inspect(f)
'[Function: f]'
> util.inspect(af)
'[AsyncFunction: af]'

CodePudding user response:

Here you go.

class a {}
var aStr = a.toString();
alert(`'${aStr}' is a class: ${aStr.indexOf('class') > -1}`);
  • Related