【问题标题】:"SyntaxError: Unexpected token ' in JSON at position 0" when requiring a module using strict mode“SyntaxError: Unexpected token ' in JSON at position 0” 当需要使用严格模式的模块时
【发布时间】:2017-05-12 23:47:49
【问题描述】:

index.js我有

'use strict';

const config = require('./config');

config.js我有

'use strict';

const config = new function() {
  this.port = 3000;
  this.redirectUri = "http://localhost:" + this.port + "/auth";
}

module.exports = config;

在运行节点 v6.9.5 的 x64 Windows 上,它运行良好。

然而,在运行节点 6.10.2 的 Raspberry Pi Zero(Raspbian Pixel,ARM v6)上,我收到以下错误:

module.js:590
    throw err;
    ^

SyntaxError: /home/pi/pihas-api/config.json: Unexpected token ' in JSON at position 0
    at Object.parse (native)
    at Object.Module._extensions..json (module.js:587:27)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/home/pi/pihas-api/index.js:8:16)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)

我知道这是因为我在 config.js 中使用了 'use strict';,但我想知道为什么它确实在 Windows 上工作,以及是否有办法让它也可以在 Pi Zero 上工作。

【问题讨论】:

  • 你为什么要new function() { ... }
  • 我不想单独导出我的所有配置consts,所以我尝试将它们全部放入同一个对象中。但是,这不允许我一次性初始化对象,因为在初始化期间我无法访问 port const inside 配置对象,所以我想我会使用一个函数相反,它确实允许我在初始化期间使用port const,并且仍然允许我从index.js 调用config.port

标签: javascript json node.js module strict


【解决方案1】:

JSON 不是 Javascript。你不能在 JSON 中"use strict";

【讨论】:

  • 我的错,它实际上是config.js。我已经编辑了问题。
  • 错误信息不一致。 SyntaxError 堆栈跟踪清楚地显示该文件名为config.json
  • 啊,我的错,谢谢!我不敢相信我没有马上明白这一点。我的实际config.js 包含一些敏感数据,所以我没有将其添加到我的 git 中。
猜你喜欢
  • 1970-01-01
  • 2017-07-07
  • 2021-09-30
  • 2017-12-15
  • 2022-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多