diff --git a/doc/api/util.md b/doc/api/util.md index a8fded6b2db042..6ebc0693ee9add 100644 --- a/doc/api/util.md +++ b/doc/api/util.md @@ -371,6 +371,27 @@ added: v6.6.0 A Symbol that can be used to declare custom inspect functions, see [Custom inspection functions on Objects][]. +## util.inspectTag + + +A template literal tag that ensures each replacement in a template string is +passed through `util.inspect()`. + +```js +const inspectTag = require('util').inspectTag; +const obj = {a: 1}; + +// Without the tag: +console.log(`${obj}`); + // Prints: '[object Object]' + +// With the tag: +console.log(inspectTag`${obj}`); + // Prints: '{ a : 1 }' +``` + ## Deprecated APIs The following APIs have been deprecated and should no longer be used. Existing diff --git a/lib/util.js b/lib/util.js index 46cde4d85bf28b..58a709e0223d12 100644 --- a/lib/util.js +++ b/lib/util.js @@ -1054,3 +1054,18 @@ exports._exceptionWithHostPort = function(err, // process.versions needs a custom function as some values are lazy-evaluated. process.versions[exports.inspect.custom] = (depth) => exports.format(JSON.parse(JSON.stringify(process.versions))); + +// A template literal tag that ensures that string literal elements +// are passed through the util.format mechanism. +// Example use: +// inspectTag`This is object ${obj}` +function inspectTag(strings, ...keys) { + var ret = ''; + for (var n = 0; n < strings.length; n++) { + ret += strings[n]; + if (n < keys.length) + ret += exports.inspect(keys[n]); + } + return ret; +} +exports.inspectTag = inspectTag; diff --git a/test/parallel/test-util-inspecttag.js b/test/parallel/test-util-inspecttag.js new file mode 100644 index 00000000000000..796a37e8ecf9ef --- /dev/null +++ b/test/parallel/test-util-inspecttag.js @@ -0,0 +1,13 @@ +'use strict'; + +require('../common'); +const assert = require('assert'); +const util = require('util'); + +const inspectTag = util.inspectTag; + +const obj = {a: 1}; + +assert.strictEqual(`${obj}`, '[object Object]'); +assert.strictEqual(inspectTag`${obj}`, '{ a: 1 }'); +assert.strictEqual(inspectTag`${obj}-${obj}`, '{ a: 1 }-{ a: 1 }');