PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 23, 2022

[FIXED] How to require .json file with module.exports in nodeJS

 July 23, 2022     javascript, json, node.js     No comments   

Issue

im used to creating .json files this way

module.exports = [
{"year":2007,"month":1,"startDate":"2007-01-01","endDate":"2007-01-31"},
{"year":2007,"month":2,"startDate":"2007-02-01","endDate":"2007-02-28"},
{"year":2007,"month":3,"startDate":"2007-03-01","endDate":"2007-03-31"},
]

I then require them like this.

var dates = require('./JSON/dates.json');

this has always worked in the past when i was working with nodejs and grunt to build websites. But now im using nodeJS to create a server app i get this message

SyntaxError: G:\Navision Reports\JS ReportServer\JSON\dates.json: Unexpected token message. I dont understand what's going on. It is working perfectly with .js files.

Please anyone knows why this no longer works? I know i could have a json object if i just remove var dates = require('./JSON/dates.json'); and make the file into one json object, but I'd really rather not reorganise all this data.


Solution

This isn't valid JSON file, you can check in any code formatter that it has syntax errors:

module.exports = [
{"year":2007,"month":1,"startDate":"2007-01-01","endDate":"2007-01-31"},
{"year":2007,"month":2,"startDate":"2007-02-01","endDate":"2007-02-28"},
{"year":2007,"month":3,"startDate":"2007-03-01","endDate":"2007-03-31"},
]

Please format your JSON in valid way and then require it or change dates.json to dates.js.

If you save file as .json you don't have to use module.exports, you actually can't, because node has built-in support for requiring .json files. You don't even have to use JSON.parse.



Answered By - Daniel Kmak
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing