【问题标题】:JSON.parse gives error on gulp taskJSON.parse 在 gulp 任务上给出错误
【发布时间】:2015-05-19 13:19:06
【问题描述】:

我有这个 gulp 任务

gulp.task('replace', function () {  
  // Get the environment from the command line
  var env = args.env || 'localdev';

  // Read the settings from the right file
  var filename = env + '.json';
  console.log(filename)

  var settings = JSON.parse(fs.readFileSync('./config/' + filename, 'utf8'));

// Replace each placeholder with the correct value for the variable.  
  gulp.src('./js/constants.js')  
    .pipe(replace({
      patterns: [
        {
          match: 'apiUrl',
          replacement: settings.apiUrl
        }
      ]
    }))
  .pipe(gulp.dest('./js'));
});

当我执行我的代码时,我总是得到这个错误

SyntaxError: Unexpected token /
  at Object.parse (native)
  at Gulp.<anonymous> (/home/k1ngsley/Projects/loanstreet-rea-app/gulpfile.js:86:23)
  at module.exports (/home/k1ngsley/Projects/loanstreet-rea-app/node_modules/gulp/node_modules/orchestrator/lib/runTask.js:34:7)
  at Gulp.Orchestrator._runTask (/home/k1ngsley/Projects/loanstreet-rea-app/node_modules/gulp/node_modules/orchestrator/index.js:273:3)
  at Gulp.Orchestrator._runStep (/home/k1ngsley/Projects/loanstreet-rea-app/node_modules/gulp/node_modules/orchestrator/index.js:214:10)
  at Gulp.Orchestrator.start (/home/k1ngsley/Projects/loanstreet-rea-app/node_modules/gulp/node_modules/orchestrator/index.js:134:8)
  at /usr/lib/node_modules/gulp/bin/gulp.js:129:20
  at process._tickCallback (node.js:448:13)
  at Function.Module.runMain (module.js:499:11)
  at startup (node.js:119:16)
  at node.js:935:3

但如果我删除 JSON.parse 并运行

var settings = fs.readFileSync('./config/' + filename, 'utf8');

我没有收到任何错误,但代码没有被解析为 json。我该怎么办?为什么 JSON.parse 在 gulpfile.js 中不起作用

任何帮助表示赞赏

【问题讨论】:

  • 错误不够明确吗?解析配置文件时出现解析错误,不是吗?文件内容是什么?

标签: json angularjs gulp


【解决方案1】:

通过这样做解决了这个错误

var setting = fs.readFileSync('./config/' + filename, 'utf8');
 var settings = JSON.parse(JSON.stringify(setting));

【讨论】:

  • 我在SyntaxError: Unexpected token 中遇到了类似的错误。这是某种空格编码的恶作剧,所以我使用了JSON.stringify(setting.replace(/\s+/g, " ")),它奏效了。
  • @Josh 这正是我的问题所在,多么奇怪……你能解释一下为什么会这样吗?
  • 有些空白字符可能不会显示在您的编辑器中,但不是有效的 JSON。 /\s+/g, " " 替换将它们全部转换为空格(在 JSON 中有效)。
猜你喜欢
  • 2017-04-12
  • 1970-01-01
  • 2015-03-25
  • 1970-01-01
  • 2015-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-10
相关资源
最近更新 更多