0

I am a newbie in Node JS and trying to get my head around functional programming. I have the following code in a file called findinfo.js and I'm trying to pass the result to the main server.js:

const fs = require('fs');
const values = ["yes", "no", "?", "unknown", "partial"];
var cInfo = [];

function getFile (cb) {
    fs.readFile('./scripts/blahblah.json', 'utf-8', function (err, jfile) {
        if (err) {
            throw new Error (err);
        }
        console.log("Function is executing...")
        JSON.parse(jfile);
        console.log('Parsing file done');
        cb(jfile);
    });
}

Then I'm trying to call this function from server.js,

var findinfo = require('./findinfo');
console.log(getFile());

which as expected crashes the program.

So what changes should I make in order to make it work?

EMichael
  • 95
  • 1
  • 9

1 Answers1

0

You need to export getFile so it can be imported using require.

const fs = require('fs');
const values = ["yes", "no", "?", "unknown", "partial"];
var cInfo = [];

function getFile (cb) {
    fs.readFile('./scripts/blahblah.json', 'utf-8', function (err, jfile) {
        if (err) {
            // throw new Error (err); // don't throw inside async callback
            return cb(err);
        }
        console.log("Function is executing...")
        JSON.parse(jfile);
        console.log('Parsing file done');
        cb(null, jfile);
    });
}

module.exports = getFile;

server.js

var getFile = require('./findinfo');

getFile(function(err, file) {
   console.log(err, file);
});

since getFile is an asynchronous function, you have to wait until it finishes, when cb is called, to console.log the result.

And using throw in a asynchronous callback is not recommended, since it will crash the server, it's recommended to pass the error to the callback.

You should take a look at this question, so you learn more about how to handle asynchronous code.

How do I return the response from an asynchronous call?

Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98