Node.js模块中的可选链运算符(?.)在Ubuntu系统无法运行
可选链运算符(?.)语法错误:SyntaxError: Unexpected token .
问题场景
在Ubuntu机器上运行代码时,使用?.可选链运算符触发语法错误。
涉及代码片段
const contentType = response?.headers['content-type'];
完整报错信息
SyntaxError: Unexpected token . at Module._compile (internal/modules/cjs/loader.js:723:23) at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10) at Module.load (internal/modules/cjs/loader.js:653:32) at tryModuleLoad (internal/modules/cjs/loader.js:593:12) at Function.Module._load (internal/modules/cjs/loader.js:585:3) at Module.require (internal/modules/cjs/loader.js:692:17) at require (internal/modules/cjs/helpers.js:25:18) at Object. (/home/pranav/mona/monacip-backend/node_modules/@api.video/nodejs-client/lib/index.js:15:38) at Module._compile (internal/modules/cjs/loader.js:778:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
原因分析
?.可选链运算符是ES2020标准新增的语法特性,当前使用的Node.js版本过低,不支持该语法。从报错栈文件版本判断,Node.js版本大概率在12.x以下(Node.js 14及以上版本才默认支持ES2020语法,Node.js 12需手动开启实验性标志)。此外,报错来自@api.video/nodejs-client依赖包代码,说明该包发布时未对ES2020语法做转译,导致旧版本Node.js无法解析。
解决办法
升级Node.js版本(推荐)
将Node.js升级到14.x及以上的长期支持(LTS)版本,比如18.x或20.x,即可原生支持?.运算符。替换为传统判断语法
若无法升级Node.js,可把可选链语法替换为传统的存在性判断:const contentType = response && response.headers && response.headers['content-type'];若报错来自第三方依赖,可尝试查找该依赖兼容旧Node.js版本的历史版本,或用Babel等工具对依赖包代码进行转译。
内容的提问来源于stack exchange,提问作者Pranav Mehta
相关产品推荐
相关产品推荐

