Converting `grunt.file.readJSON` to gulp

901 Views Asked by At

I'm in the process of converting a Grunt file to a Gulp file. My Grunt file contains the following line

var config = grunt.file.readJSON('json/config.json');

What this line is doing is that it is setting some variables which it then injects into the html it generates, specifically related to languages.

I tried converting the file automatically with grunt2gulp.js but it always fails with config being undefined. How would I write grunt.file.readJSON using gulp?

2

There are 2 best solutions below

3
Benjamin Gruenbaum On BEST ANSWER

The easiest way to load a JSON file in node/io.js is to use require directly:

var config = require('json/config.json');

This can substitute any readJSON calls you have and also works generally. Node/io.js have the ability to synchronously require json files out of the box.

3
Mike 'Pomax' Kamermans On

Since this is a .json file, Benjamin's answer works just fine (just require() it in).

If you have any configs that are valid JSON but not stored in files that end in a .json extension, you can use the jsonfile module to load them in, or use the slightly more verbose

JSON.parse(require('fs').readFileSync("...your file path here..."))

(if you have fs already loaded, this tends to be the path of least resistance)

The one big difference between require (which pretty much uses this code to load in json files) and this code is that require uses Node's caching mechanism, so multiple requires will only ever import the file once, and then return points to the parsed data, effectively making everything share the same data object. Sometimes that's great, sometimes it's absolutely disastrous, so keep that in mind

(If you absolutely need unique data, but you like the convenience of require, you can always do a quick var data = require("..."); copied = JSON.parse(JSON.stringify(data));)