[英]Heredoc usage in Node.js
我有以下Node.js代码和输出:
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
如何在v<interpolate here>
处在heredoc中进行v<interpolate here>
? 我的目标是用1.2.0
替换<interpolate here>
。
我也更喜欢使用一个弯曲的heredoc 。 例如,现在我必须写:
if (true) {
var help = `foo bar baz
cats and dogs
`
}
但我宁愿这样写:
if (true) {
var help = `foo bar baz
cats and dogs
`
}
如何创建不尊重第一个换行符的Heredoc? 例如,现在我必须写:
var help = `Usage: foo [options]
...
但我宁愿这样写:
var help = `
Usage: foo [options]
...
最后,heredoc文档在哪里?
在Node中,一般没有heredocs,特别是没有杂乱的heredocs,因此没有关于它的文档。
ES6中有模板文字:
它们在Node 6.x +中可用-请参阅兼容性列表:
您可以使用一些技巧来使缩进保持所需的样子,例如:
删除前4个字符:
let x = `
abc
def
`.split('\n').map(l => l.slice(4)).join('\n');
console.log(`"${x}"`);
删除前4个字符和空行:
let x = `
abc
def
`.split('\n').map(l => l.slice(4)).filter(l => l).join('\n');
console.log(`"${x}"`);
使用正则表达式替换从行首删除所有空格:
let x = `
abc
def
`.replace(/^\s+/igm, '');
console.log(`"${x}"`);
您可以使用${ expression }
插入模板文字中的任何JavaScript表达式,如下所示:
let x = `2 + 2 = ${2 + 2}`;
console.log(`"${x}"`);
它不仅适用于变量,而且如果需要,表达式当然可以是单个变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.