Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS calling readline within a function

Tags:

node.js

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..

like image 585
toti Avatar asked Jun 07 '26 02:06

toti


1 Answers

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
like image 157
Kapulara Avatar answered Jun 08 '26 22:06

Kapulara