node util inspect object method and other options for converting an object to a string.

When making a nodejs project or any javaScript project for that matter there comes a time now and then to convert an object to a string representation of that object. In nodejs there is the node inspect method in the core nodejs util module, there are other ways of doing so such as using the JSON stringify method.

1 - Util inspect method

For a basic example of the node util inspect object method here I have just a plain old object literal that I am passing to the util inspect method. The returned result is then as expected, a string representation of the object.

1
2
3
4
5
6
7
8
let obj = {
x: 42,
y: 30
};
let str = util.inspect(obj);
console.log(typeof str); // string
console.log(str); // { x: 42, y: 30 }

2 - JSON stringify to convert an object to a string

Another way to create a strung representation of an object would be to just use the JSON.strignify method.

1
2
3
4
5
6
7
8
let obj = {
x: 42,
y: 30
};
let str = JSON.stringify(obj);
console.log(typeof str); // string
console.log(str); // { x: 42, y: 30 }