0

I'm trying to use json-server to generate some fake data. Here is the Node.js code:

// data.js
function generateData1() {
    test = [];
    return {
        "test": test
    }
}


function generateData2() {
    test = [];
    return {
        "test": test
    }
}

module.exports = {
    generatePredixData: generatePredixData1,
    generatePredixLatestData: generatePredixData2
}

When trying to run json-server data.js it throws the following error:

the database is a javascript file but the export is not a function

Here is the full stack trace:

D:\FakeData>json-server data.js

  \{^_^}/ hi!

  Loading data.js
C:\Users\jay.r\AppData\Roaming\npm\node_modules\json-server\lib\cli\utils\load.j
s:28
      throw new Error('The database is a JavaScript file but the export is not a
 function.');
      ^

Error: The database is a JavaScript file but the export is not a function.
    at module.exports (C:\Users\jay.r\AppData\Roaming\npm\node_modules\json-serv
er\lib\cli\utils\load.js:28:13)
    at start (C:\Users\jay.r\AppData\Roaming\npm\node_modules\json-server\lib\cl
i\run.js:119:5)
    at module.exports (C:\Users\jay.r\AppData\Roaming\npm\node_modules\json-serv
er\lib\cli\run.js:156:3)
    at module.exports (C:\Users\jay.r\AppData\Roaming\npm\node_modules\json-serv
er\lib\cli\index.js:76:3)
    at Object.<anonymous> (C:\Users\jay.r\AppData\Roaming\npm\node_modules\json-
server\lib\cli\bin.js:3:14)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
iJade
  • 23,144
  • 56
  • 154
  • 243

1 Answers1

1

If someone comes across this, the guy was basically passing an object to json-server. This library just wants a function as export, so that's why it wasn't working.

From the docs

Using JS instead of a JSON file, you can create data programmatically.

// data.js
module.exports = () => {
  const data = { users: [] }
  // Create 1000 users
  for (let i = 0; i < 1000; i++) {
    data.users.push({ id: i, name: `user${i}` })
  }
  return data
};

Start JSON Server

json-server --watch data.js

So basically the output sholud always be a sort-of json database. Which means he could even split the functions to generate different parts of the data, but in the end a single function should have been exported.

E.G.

// data.js
function generateData1() {
    test = [];
    return {
        "test": test
    }
}


function generateData2() {
    test = [];
    return {
        "test": test
    }
}

module.exports = () => {
    return {
        generated1: generateData1(),
        generated2: generateData2()
    };
};

And then he would have got

GET /generated1

and

GET /generated2

Sampgun
  • 2,822
  • 1
  • 21
  • 38