Search code examples
node.jses6-promise

npm firstline package do not return first line (string) but a promise object, how to get the first line string?


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?


Solution

  • 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