0

I built a vanilla Node server with Express.js just to parse a JSON file and return an array => http://localhost:3000

Vis a vis, i've built a Vue client on http://localhost:8080, with an axios get request calling the Node server address above

index.js

const express = require('express');
const app = express();
const port = 3000;
let fs = require('fs');

app.get('/', (request, response) => {
    function parseMeGood() {
        fs.readFile('./cityList.json', 'utf8', function (err, data) {
            if (err) throw err;
            let cityArr = [];
            let obj = JSON.parse(data);
            let city;
            for (city of obj) {
                if (city.name === 'Huntsville') {
                    cityArr.push({"country": city.country});
                }
            }
            // console.log(cityArr);
            return cityArr;
        });
    }

    response.send(parseMeGood());
});

app.listen(port, (err) => {
    if (err) {
        return console.log('something bad happened', err)
    }
    console.log(`server is listening on ${port}`)
});
  • call is good, i'm using Moesif to disable CORS and getting 200
  • I console.log(cityArr); and it's working perfect on the server side.
  • A regular string does pass (response.send('testing123');) and all is good.
  • I also know that synchronous functions such as using JSON.parse() can delay Node's Asynchronous nature and it's not that "Nodey" to do, but I also know that there is no issue doing it.

Please correct my ways so I will be strong with the force again.

Community
  • 1
  • 1
clusterBuddy
  • 1,523
  • 12
  • 39
  • Just replace `return cityArr;` with `response.send(cityArr);`. That should do it. – ibrahim mahrir Apr 28 '18 at 17:30
  • When you use return in a callback to an asynchronous function, it doesn't return that from actual outer function (so `parseMeGood()` will return nothing here) – Abid Hasan Apr 28 '18 at 17:36

1 Answers1

0
app.get('/', (request, response) => {
    fs.readFile('./cityList.json', 'utf8', function (err, data) {
            if (err) response.status(500).send();
            let cityArr = [];
            let obj = JSON.parse(data);
            let city;
            for (city of obj) {
                if (city.name === 'Huntsville') {
                    cityArr.push({"country": city.country});
                }
            }
            response.send(cityArr);
        });
});
Rodrigo Manguinho
  • 1,411
  • 3
  • 21
  • 27