简体   繁体   中英

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?

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:

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

Indentation

You can use some tricks to keep the indentation how you want it though, eg:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM