toti
toti

Reputation: 157

NodeJS calling readline within a function

I'm learning NodeJS and I encounter a basic issue. I'm trying to read a file line by line, and for each line I read to send an HTTP request to / + <the line> e.g.:

wlist.txt contents

line 
line2

failed attempt:

const request = require('request') // for http request later
const readline = require('readline')
const fs = require('fs')
function fileLoader() {
  const readInterface = readline.createInterface({
    input: fs.createReadStream('C:\\etc\\code\\req\\wlist.txt'),
  });
  readInterface.on('line', function(line) {
    return "test";
  });
}

var aba = fileLoader();
console.log(aba); // undefined

My logic inserting fileLoader as a function and not "as is" is that I later on have a switch case that uses the file load to different purposes such as XML request or JSON request.. lets say:

switch (myArgs[0]) {
  case 'json':
  let myJSON = {username: 'val'};
  request({
  url: "http://192.168.1.2:3000",
  method: "POST",
  json: true,
  body: myJSON
  }, function (error, response, body){
    console.log(response.headers)
    console.log(response.body)
  });
    break;

  case 'xml': .....

I'm fully aware theres something I missing, probably regarding async / promises or anything, but to really educate, may someone please go easy on me and show me the way? I've tried everything and just can't get a grasp of whats the problem..

Upvotes: 3

Views: 565

Answers (3)

user2771365
user2771365

Reputation: 133

readline is asynchronous so chances are that console.log is being called before fileLoader has finished. Try using readline-sync if you are happy to block whilst the file is read.

Otherwise you should re-write so the the on('line',...) method performs the action you want to take with the line as it is read. (I think this is what you want - "read a file line by line, and for each line I read to send an HTTP request"). E.g.

on('line', (input) => { /* perform send http stuff/call function to do it */ } );

Or, if you only want to act when the whole file is read, you'll have to re-structure so that the file-read is wrapped in a promise (or use async/await).

Upvotes: 0

Kapulara
Kapulara

Reputation: 301

I believe you would like to do something like this: https://gist.github.com/EB-BartVanVliet/533d55eb17c97f2a12ed25f479786f4a

Essentially what I do is:

  • Parse the file, look for empty lines and remove those
  • I declare a async start function so that I can use await inside the for loop
  • Log the output

Upvotes: 1

Sang Huynh
Sang Huynh

Reputation: 241

You can do simple like this:

var sendRequest = function (input) {
  // Do whatever you want here 
}
var lineReader = require('readline').createInterface({
  input: require('fs').createReadStream('path_to_your_file')
});

lineReader.on('line', function (line) {
  console.log('Line from file:', line);
  sendRequest(line);
});

Upvotes: 0

Related Questions