0

I am trying to extract the first line of a file using npm firstline (https://www.npmjs.com/package/firstline) package using the following line of code

const firstline = require("firstline");
console.log("First line of the file: " + firstline("home/assets/sample.txt");

however it returns First line of the file: [object Promise] as output.

content of file "home/assets/sample.txt" is as follows

abc
def
ghi

Therefore, I expect "abc" as output. what I am missing?

Wasim Aftab
  • 638
  • 1
  • 8
  • 16

2 Answers2

0

Promises in javascript need to be resolved to get the value out of them:

const firstline = require("firstline");
firstline("home/assets/sample.txt").then(line => {
  console.log("First line of the file: " + line);
});

As shown above you can use .then or await to get the value out.

Example using await:

const firstline = require("firstline");

const main = async () => {
  const line = await firstline("home/assets/sample.txt");
  console.log("First line of the file: " + line);
};

main();

note that await need to be in an async function to work, otherwhise you will have a javascript syntax error

kigiri
  • 2,952
  • 21
  • 23
0

Since the firstline package returns a promise you cannot just console.log the result. Instead you can use then or await.

Maybe this can answer your question.

How does .then(console.log()) and .then(() => console.log()) in a promise chain differ in execution

Pavlos Klonis
  • 151
  • 2
  • 4