Search code examples
javascriptasynchronouspromiseasync-awaites6-promise

<Buffer 72 65 74 72 69 65 76 65 72> Please explain what's It's mean in js


I am practicing javascript and wants to know about <Buffer 72 65 74 72 69 65 76 65 72> error.

I was reading data from a file called dog.txt. I find out that when I put "data" in the console.log then I saw this <Buffer 72 65 74 72 69 65 76 65 72> error. I know the solution is to put "${data}" in the console.log to get the expected result. Actually I wanted to know what <Buffer 72 65 74 72 69 65 76 65 72> mean.

Here is the code

    return new Promise ((resolve,reject)=>{
        fs.readFile(file,(err,data)=>{
            if(err){reject("Data cannot be found")}else
            resolve(data);
        })
    })
}



const getdata=async()=>{
    try{
        const data=await ReadfilePro(`./dog.txt`);
    console.log(data);
    }catch(err){
        console.log(err);
    }
}

getdata();

here dog.txt file just contains this dog name "retriever" without quotes.

As a result of the above code, I got this in the console <Buffer 72 65 74 72 69 65 76 65 72>.

I hope you will give a detailed answer and Sorry if it is a dumb question.

I don't want the solution I want an explanation. Thanks


Solution

  • What you are reading is a buffer of bytes. NodeJS cannot and will not make the assumption that you are reading a string, as that is a much more difficult assumption to justify than one thinks.

    The reasoning behind this is that readFile is on one of the lowest levels of abstraction available to you. it is expected for people to write code on top of this if they know the format of their data.

    Fortunately for you, there are conversion methods. Suppose you know your buffer is valid utf8, calling data.toString('utf8') will attempt to convert your buffer to utf8.