I have the following Node.js code and output:
var help = `Usage: foo [options]
v<interpolate here>
Options:
-h, --help Show some help
`
process.stdout.write(help)
var packageDotJson = require('./package.json');
process.stdout.write(packageDotJson.version + "\n")
// Usage: foo [options]
//
// v<interpolate here>
//
// Options:
// -h, --help Show some help
// 1.2.0
How can I interpolate in the heredoc at v<interpolate here>
? My goal is to replace <interpolate here>
with 1.2.0
.
I would also prefer to use a squiggly heredoc. For example, now I have to write:
if (true) {
var help = `foo bar baz
cats and dogs
`
}
but I'd rather write:
if (true) {
var help = `foo bar baz
cats and dogs
`
}
How can I create a heredoc that doesn't respect the first newline? For example, now I have to write:
var help = `Usage: foo [options]
...
but I'd rather write:
var help = `
Usage: foo [options]
...
Finally, where is the heredoc documentation?
In Node there are no heredocs in general and squiggly heredocs in particular so there is no documentation about it.
There are template literals in ES6:
They are available in Node 6.x+ - see compatibility list:
You can use some tricks to keep the indentation how you want it though, e.g.:
Remove first 4 chars:
let x = `
abc
def
`.split('\n').map(l => l.slice(4)).join('\n');
console.log(`"${x}"`);
Remove first 4 chars and empty lines:
let x = `
abc
def
`.split('\n').map(l => l.slice(4)).filter(l => l).join('\n');
console.log(`"${x}"`);
Remove all whitespace from beginning of lines using regex substitution:
let x = `
abc
def
`.replace(/^\s+/igm, '');
console.log(`"${x}"`);
You can interpolate any JavaScript expression in a template literal with ${ expression }
like this:
let x = `2 + 2 = ${2 + 2}`;
console.log(`"${x}"`);
It's not only for variables but of course the expression can be a single variable if you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With