Search code examples
javascriptjsonjson-server

SyntaxError: Unexpected token 'm', "module.exp"... is not valid JSON


$ npx json-server --version
1.0.0-alpha.23
$ node -v
v20.12.0
$ ls
generate.js  node_modules  package.json  package-lock.json  public  README.md  src

I am trying to run a React project on my local from GitHub repo. I have installed almost all dependencies, but having issues running a .js file with json-server.

The file I am trying to load via json-server is below: https://github.com/brucevanhorn2/reactstrap-course/blob/master/generate.js

Here's the error I am getting in VS Code terminal after running the command: npx json-server generate.js

undefined:1
module.exports = function(){
^

SyntaxError: Unexpected token 'm', "module.exp"... is not valid JSON
    at JSONFile.parse (<anonymous>)
    at JSONFile.read (file:///home/niveus/PRAKASH/VS_CODE/flying_cars/node_modules/lowdb/lib/adapters/node/DataFile.js:17:31)
    at async Observer.read (file:///home/niveus/PRAKASH/VS_CODE/flying_cars/node_modules/json-server/lib/observer.js:21:22)
    at async Low.read (file:///home/niveus/PRAKASH/VS_CODE/flying_cars/node_modules/lowdb/lib/core/Low.js:16:22)
    at async file:///home/niveus/PRAKASH/VS_CODE/flying_cars/node_modules/json-server/lib/bin.js:114:1

Node.js v20.12.0

I have tried different ways of export like export default () => {} in generate.js file, but still no luck.

What could have gone wrong here?


Solution

  • Like several other features, loading a JS file to Generate random data is not (or at least not yet) supported by json-server@1, the alpha release currently being published to npm as latest. This version only accepts a JSON file, hence the syntax errors on non-JSON content. So either:

    • Use that file just to generate the JSON, then save it as JSON for use by json-server; or
    • Install json-server@0 to get the stable version (currently v0.17.4).

    Related: