svegger
svegger

Reputation: 21

How to correctly import a function, returning Promise? NodeJS

there's a promise-returning function fileToArray(). It successfully works in its original js file. But if i export it and import in another file, it doesn't: i receive error. Code in orig file:

function fileToArray(Object) {
    return new Promise((resolve, reject) => {
        const rl = readline.createInterface({
            input: fs.createReadStream(Object.file),
            crlfDelay: Infinity
        });
        rl.on('line', line => Object.array.push(line));
        rl.on('close', () => resolve(Object.array));
        rl.on('error', err => reject(err))
    });
}

fileToArray({file:"./maleNames.txt",array:[]}).then(lines => console.log(lines));
//^^ works, returns full array

module.exports = fileToArray; //export line

there's code where i import it:

const fileToArray = require('./myLib');
fileToArray({file:"./maleNames.txt",array:[]}).then(lines => console.log(lines));

and error after execution:

fileToArray({file:"./maleNames.txt",array:[]}).then(lines => console.log(lines));
                                              ^
TypeError: Cannot read property 'then' of undefined

Upvotes: 0

Views: 841

Answers (1)

svegger
svegger

Reputation: 21

i changed construction of import and export. Error fixed

  1. Export module.exports.fta = fileToArray;
  2. Import let myLib = require('./myLib'); ...then used myLib.fta()

Upvotes: 1

Related Questions