javascript 不能在 node.js 中使用模板字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32844871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can't use template strings in node.js
提问by Electric Coffee
According to MDN, Template Stringsshouldbe working in Chrome, and by extension V8 on which Node.js is based on; but when I try the following I get a syntax error:
根据 MDN,模板字符串应该在 Chrome 中工作,并且通过扩展,Node.js 基于的 V8;但是当我尝试以下操作时,出现语法错误:
var name = 'coffee';
console.log(`Hello, ${name}!`);
running node file.js
just results in a SyntaxError: Unexpected token ILLEGAL
运行node file.js
只会导致SyntaxError: Unexpected token ILLEGAL
Is there some kind of flag I need to enable to use this feature, or is it simply not implemented in node?
是否需要启用某种标志才能使用此功能,还是根本没有在节点中实现?
回答by T.J. Crowder
Template strings were added in NodeJS v4.0.0. And I can confirm that they do work at least as far back as v4.1.1; I didn't bother to check v4.0.0, but I have no reason to doubt the linked announcement. No special runtime flag is required.
在NodeJS v4.0.0中添加了模板字符串。我可以确认它们至少可以追溯到 v4.1.1;我没有费心检查 v4.0.0,但我没有理由怀疑链接的公告。不需要特殊的运行时标志。
回答by Rahul Soshte
I am using NodeJS v10.16.0 and template strings are not working in mine. So I had a workaround. I wrote the code this way.
我正在使用 NodeJS v10.16.0 并且模板字符串在我的中不起作用。所以我有一个解决方法。我是这样写代码的。
const util = require('util');
var name = 'coffee';
console.log(util.format(`Hello, %s!`,name));
%s - String.
%d - Number (both integer and float).
%j - JSON.
%% - single percent sign ('%'). This does not consume an argument.
%s - 字符串。
%d - 数字(整数和浮点数)。
%j - JSON。
%% - 单个百分号 ('%')。这不消耗参数。