Search code examples
javascriptnode.jsstringfilereadfile

How to turn a file into a string in NodeJS


I am attempting to convert a text file (on my machine) into a string. What is the best/simplest way to do this? I am looking for a basic function that would look like this:

function fileToString(filepath) {
   //this returns a string with the contents of the file
}

How should I do this?

EDIT: I now know that there is another question that asks this, but I didn't understand that question so I asked it in different words.


Solution

  • You need node.js for that and this code:

    const fs = require('fs')
    
    const fileContents = fs.readFileSync('./myFile').toString()