Kingsley Simon
Kingsley Simon

Reputation: 2210

JSON.parse gives error on gulp task

I have this gulp task

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'));
});

I always get this error when i execute my code

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

But if i remove the JSON.parse and just run

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

I get no error but the code is not parsed as json. What do i do? Why does JSON.parse not work in gulpfile.js

Any help appreciated

Upvotes: 1

Views: 2357

Answers (1)

Kingsley Simon
Kingsley Simon

Reputation: 2210

Solved this error by doing this

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

Upvotes: 4

Related Questions