I'm having some problems getting the asynchronous nature of node to co-operate with me, and after hours of callbacks and googling; I finally turn to you guys.
I have a program that needs to read in lines from a file using the readline module of node. This file contains data that is passed to some asynchronous functions defined within my node program. Once all the data is successfully read and processed, this data needs to be parsed into JSON format, and then outputted.
My problem here is that when I call: readLine.on('close', function() { ...... }, this is run before the asynchronous functions finish running, and therefore I am left with an output of nothing, but the program keeps running the asynchronous functions.
I've created a simple skeleton of functions that should explain my situation more clearly:
function firstAsyncFunc(dataFromFile) { //do something asynchronously return processedData; } function secondAsyncFunc(dataFromFile) { //do something else asynchronously return processedData; } //create readline var lineReader = require('readline').createInterface({ input: require('fs').createReadStream('data.txt') }); //array to hold all the data processed var totalDataStorage; //read file lineReader.on('line', function(line) { var processedData = firstAsyncFunction(line); var moreProcessedData = secondAsyncFunction(line); //store processed data and concatenate into one array var tempDataStorage = [{ 'first': processedData, 'second': moreProcessedData }] totalDataStorage = totalDataStorage.concat(tempDataStorage); }).on('close', function() { var JSONString = JSON.stringify(... //create JSON for totalDataStorage ...); console.log(JSONString); //DOESN'T OUTPUT ANYTHING! }); I have tried to add a callback to the first/secondAsynFunction, I have tried to make the reading and parsing bit of the program seperate functions, and create callbacks so that parsing is only called when reading finished, but none of those solutions seemed to be working and i'm really struggling - so any help would be appreciated.
Thanks!
EDIT: The data.txt file is of the form
IPData1 DataCenter1 IPData2 DataCenter2 ... IPDataN DataCenterN I use str.split(" ") to get the respective values, and then pass them appropriately. IPData is a number, and DataCenter is a string
IPData, DataCentre. In the actual program, I use str.split(" "), to split the two values, and then pass them into the necessary function. The IPData is a number, and the DataCentre value is a string. Hope this helpsvar processedData = firstAsyncFunction(line);makes no sense at all. Also, it can be done very easily in a few rows usingfs.readFile.