18

I am fairly new to JS and I have a JSON file that I need to send to my server (Express) that I can then parse and use its contents throughout the web app I'm building.

Here's what I have now:

  • a JSON file named data.json
  • an Express server set up that is running on a localhost
  • some shitty code:
    app.get('/search', function (req, res) {
     res.header("Content-Type",'application/json');
     res.send(JSON.stringify({/data.json/}));
    });

In the code above I am just trying to send the file to localhost:3000/search and see my JSON file, but all I receive when I go to that path is { }. Can anyone explain?

Any help would be immensely appreciated. Thanks so much in advance.

Cheers, Theo

Example snippet from data.json:

[{
    "name": "Il Brigante",
    "rating": "5.0",
    "match": "87",
    "cuisine": "Italian",
    "imageUrl": "/image-0.png"
}, {
    "name": "Giardino Doro Ristorante",
    "rating": "5.0",
    "match": "87",
    "cuisine": "Italian",
    "imageUrl": "/image-1.png"
}]
Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93
Theo Strauss
  • 1,281
  • 3
  • 19
  • 32
  • for sending a file as response object, check accepted ans here : https://stackoverflow.com/questions/7288814/download-a-file-from-nodejs-server-using-express – Robert Rowntree Jun 30 '17 at 15:39

5 Answers5

32

Just make sure you're requiring the correct file as a variable and then pass that variable into your res.send!

const data = require('/path/to/data.json')

app.get('/search', function (req, res) {
  res.header("Content-Type",'application/json');
  res.send(JSON.stringify(data));
})

Also, my personal preference is to use res.json as it sets the header automatically.

app.get('/search', function (req, res) {
  res.json(data);
})

EDIT:

The drawback to this approach is that the JSON file is only read once into memory. If you don't want the file read into memory or you're planning on modify the JSON on disk at some point then you should see Ian's Answer

Khauri
  • 3,753
  • 1
  • 11
  • 19
  • thanks so much! weirdly, the app.get function works, but it crashes whenever i put the `const data = require('src/data.json/'). any clue? – Theo Strauss Jun 30 '17 at 15:23
  • 1
    `const data = require('./src/data.json')` – Denis Tsoi Jun 30 '17 at 15:30
  • Check your stack trace and see what it says and if it's locating the file. Remember that the require function starts looking in the directory in which the file it was called in is located, not the root of your application. – Khauri Jun 30 '17 at 15:36
  • got it to work but now getting this error: "TypeError: path must be a string or Buffer". do you think the json file is formatted incorrectly? thanks for helping me again – Theo Strauss Jun 30 '17 at 15:38
  • Based on the sample you've supplied, your json is fine. This error may be coming from somewhere else in your application. Check the error stack trace for the line number and file that's causing it. It may be coming from improper usage of the fs (filesystem) module. – Khauri Jun 30 '17 at 16:00
  • In my opinion, `res.json(data);` is much better than `res.send(JSON.stringify(data));` which return a JSON object rather than just a string. – xgqfrms Aug 29 '23 at 19:52
9

Another option is to use sendFile and set the content type header.

app.get('/search', (req, res) => {
    res.header("Content-Type",'application/json');
    res.sendFile(path.join(__dirname, 'file_name.json'));
})

The code assumes the file is in the same directory as the JS code. This answer explains how this works.

Ian
  • 7,480
  • 2
  • 47
  • 51
2

Try res.json(data.json) instead of res.send(...

user5480949
  • 1,410
  • 1
  • 15
  • 22
0

Because __dirname resolves to where your script is running I prefer using path.resolve()

var path = require('path');

app.get('/search', (req, res) => {
    res.header("Content-Type",'application/json');
    res.sendFile(path.resolve('search/data.json'));
})
Soth
  • 2,901
  • 2
  • 27
  • 27
-1

Read the file first and then send the json to the client.

fs.readFile('file_name.json', 'utf8', function (err, data) {
  if (err) throw err;
  obj = JSON.parse(data);
  res.send(JSON.stringify(obj));
});
Arpit Solanki
  • 9,567
  • 3
  • 41
  • 57
  • Hi! Thanks so much. I nested that in my app.get function. Is that what I should've done? Here is the code I have: `app.get('/search', function (req, res) { app.readFile('data.json', 'utf8', function (err, data) { if (err) throw err; obj = JSON.parse(/data.json/); res.send(JSON.stringify(obj)); }); });` I am getting an error on the localhost saying app.readFile is not a function. Any clue why? – Theo Strauss Jun 30 '17 at 15:05
  • app.readFile won't work. You first have to add a require statement. `var fs = require('fs');` Then use `fs.readFile` – Arpit Solanki Jun 30 '17 at 15:07
  • hmm what's fs? should it be 'app'? – Theo Strauss Jun 30 '17 at 15:14
  • fs (File System) is a module included in Node – user5480949 Jun 30 '17 at 15:35