Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Heredoc usage in Node.js

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?

like image 345
mbigras Avatar asked Jan 05 '23 15:01

mbigras


1 Answers

Heredocs

In Node there are no heredocs in general and squiggly heredocs in particular so there is no documentation about it.

Template literals

There are template literals in ES6:

  • https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals
  • https://developer.mozilla.org/pl/docs/Web/JavaScript/Referencje/template_strings

They are available in Node 6.x+ - see compatibility list:

  • http://node.green/#template-literals

Indentation

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}"`);

Interpolation

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.

like image 151
rsp Avatar answered Jan 13 '23 12:01

rsp