How to turn a file into a string in NodeJS

Viewed 14116

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.

4 Answers

You need node.js for that and this code:

const fs = require('fs')

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

You need to use Node.js for that. The code would be:

const fs = require('fs');
const fileName = "myFile.txt";
const fileData = fs.readFileSync(fileName, "utf8");

You cannot do this in Javascript (browser based), as it does not have access to the file system. You have to use NodeJs for the same.

var fs = require('fs');

fs.readFile('DATA', 'utf8', function(err, contents) {
    console.log(contents);
});

This willl print the contents of the file. Store the contents in a variable. JS has a .toString() function which can do what you want.

Just like how Nurbol Alpysbayev and Ashay Mandwarya said in their answers, you'll need to write Javascript for a Runtime System that supports native FileSystem access. Runtime Systems embedded in browsers (the classical way JS that runs on the browser) do not support that.

Node.js, a popular JS Runtime System, that supports so may be used. Your code for Node.js may look like this:

const fs = require('fs');

function fileToString(filepath) {
   fs.readFile(filepath, (err, data) => {
       if (err) throw err;

       return data;
   });
}
Related