Not a gulp-specific question per-se, but how would one get info from the package.json file within the gulpfile.js; For instance, I want to get the homepage or the name and use it in a task.
4 Answers
This is not gulp specific.
var p = require('./package.json')
p.homepage
UPDATE:
Be aware that "require" will cache the read results - meaning you cannot require, write to the file, then require again and expect the results to be updated.

- 11,384
- 6
- 39
- 35
-
7I definitely felt like an idiot for searching for this when I saw your answer. Of course! – spikeheap Mar 26 '15 at 10:36
-
1Worked for me :P. And +1 for the comment about caching, I later switched to using 'fs.readFileSync()` as pointed out below. – Bart Sep 25 '15 at 09:52
-
@spikeheap I don't know if I've ever laughed out loud before reading a comment on StackOverflow, but I was RIGHT there with you! Thanks for the cheers. Haha. – Modular Jun 19 '16 at 04:27
Don't use require('./package.json')
for a watch process, as using require
will resolve the module as the results of the first request.
So if you are editing your package.json
those edits won't work unless you stop your watch process and restart it.
For a gulp watch process it would be best to re-read the file and parse it each time that your task is executed, by using node's fs
method
var fs = require('fs')
var json = JSON.parse(fs.readFileSync('./package.json'))

- 118,978
- 58
- 307
- 400

- 1,661
- 1
- 12
- 11
-
4Agreed that "require" does cache the result (making it unsuitable if you intend to read/modify/read-again). That does not make it a bad solution in all cases though. The OP explicitly mentioned he wanted to read information out of it. – Mangled Deutz Apr 14 '15 at 17:56
-
4It's possible to use `require` and the remove the cache with `delete require.cache[require.resolve(FILEPATH)];` – curly_brackets May 24 '16 at 13:06
-
@KennethB Why not as separate answer? Would drive more then enough upvotes. – kaiser Jan 06 '17 at 21:08
This is a good solution @Mangled Deutz. I myself first did that but it did not work (Back to that in a second), then I tried this solution:
# Gulpfile.coffee
requireJSON = (file) ->
fs = require "fs"
JSON.parse fs.readFileSync file
Now you should see that this is a bit verbose (even though it worked). require('./package.json')
is the best solution:
Tip
-remember to add './' in front of the file name. I know its simple, but it is the difference between the require method working and not working.
If you are triggering gulp from NPM, like using "npm run build" or something
(This only works for gulp run triggers by NPM)
process.env.npm_package_Object
this should be seprated by underscore for deeper objects.
if you want to read some specific config in package.json like you want to read config object you have created in package.json
scripts : {
build: gulp
},
config : {
isClient: false.
}
then you can use
process.env.npm_package_**config_isClient**

- 916
- 7
- 17