13

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.

Moish
  • 452
  • 1
  • 3
  • 13
  • There's no such a basic function, JS (in browsers) can't directly access user's local drive system. You'd need an input type of file and FileReader API to achieve what you need. Search for these. – Teemu Dec 28 '18 at 06:33
  • 1
    Are you using node.js? – Nahiyan Dec 28 '18 at 06:33
  • There are couple existing answers https://www.bing.com/search?q=javascript+read+file+as+string (i.e. https://stackoverflow.com/questions/14446447/how-to-read-a-local-text-file) ... Or add nodejs for node versions... Or you even can go to old days and use CScript to run JavaScript like https://stackoverflow.com/questions/2840252/writing-utf8-text-to-file – Alexei Levenkov Dec 28 '18 at 06:41

4 Answers4

22

You need node.js for that and this code:

const fs = require('fs')

const fileContents = fs.readFileSync('./myFile').toString()
Nurbol Alpysbayev
  • 19,522
  • 3
  • 54
  • 89
  • 2
    fs.readFileSync('./myFile', 'utf8') returns a string. No need the .toString() https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options – Vince Dec 09 '20 at 18:56
  • 1
    Exactly! That's why it's a better practice to use the function as it is designed adding 'utf8' as encoding option. Otherwise, it returns a buffer that you have to convert into a string. Why would you ask the function to return a buffer when it can return the type you want? – Vince Dec 09 '20 at 20:56
6

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");
Mark
  • 143,421
  • 24
  • 428
  • 436
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • 1
    This answer is incorrect. `readFile` does not return file contents. On the other hand `readFileSync` does (but not a string but a buffer). – Nurbol Alpysbayev Dec 28 '18 at 07:38
  • "If the encoding option is specified then this function returns a string. Otherwise it returns a buffer." from the nodejs docs https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options. Sheesh. – Mark Dec 28 '18 at 09:18
  • I believe I have fixed it now @Mark - but the docs were a little unclear. Should it be `string ` or `utf-8`? – Jack Bashford Dec 28 '18 at 09:20
  • (filename, "utf8") – Mark Dec 28 '18 at 09:22
2

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.

ellipsis
  • 12,049
  • 2
  • 17
  • 33
  • 2
    Saying that "You cannot do this in Javascript" is incorrect and can be misleading for beginners. I think it's better to say that the browser-based JS runtime systems do not support FileSystem access. Node.js, another JS runtime system (not browser-based), supports that. – Nahiyan Dec 28 '18 at 06:37
  • 2
    Funny thing that it is possible to read files with locally running JavaScript for almost 20 years now on Windows... – Alexei Levenkov Dec 28 '18 at 06:44
  • That's true, good point. – Nahiyan Dec 28 '18 at 06:44
  • Apparently, reading wasn't enough. – ellipsis Dec 28 '18 at 06:47
  • @AlexeiLevenkov did you mean that browser-based JS can read files? IF yes, then how? I am just curious – Nurbol Alpysbayev Dec 28 '18 at 07:42
  • 1
    @NurbolAlpysbayev No, NodeJS is not the first command line runner for JavaScript available on Windows - CScript/WScript where there before 2000, .Net compiler (jsc) is there since about 2001 (https://en.wikipedia.org/wiki/JScript_.NET). You can find samples https://stackoverflow.com/questions/28881184/run-javascript-in-a-windows-command-line or if you need more info MSDN contains plenty as well as SO. Search - https://www.bing.com/search?q=cscript%20command%20javascript – Alexei Levenkov Dec 28 '18 at 21:11
  • 1
    @NurbolAlpysbayev there is also [HTA](https://en.wikipedia.org/wiki/HTML_Application) that let you run HTML pages with script as local apps with mostly full access to local resources (since 1999). – Alexei Levenkov Dec 28 '18 at 21:14
  • @AlexeiLevenkov Interesting! Yep, now I recall that there were some "script" or "scenarios" files in windows and their icon was literally a script written on papyrus or something :D – Nurbol Alpysbayev Dec 29 '18 at 05:35
-1

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;
   });
}
Nahiyan
  • 510
  • 5
  • 19
  • There is really need for yet another identical answer here in addition to plenty of other similar posts on simiar questions... At least without saying something new. – Alexei Levenkov Dec 28 '18 at 06:46
  • I answered exactly as the OP requested. No one wrote code just how the OP wanted it in form of a function. – Nahiyan Dec 28 '18 at 06:46
  • Mind explaining why you downvoted my answer even though I provided something in a different format, based on the request of the OP, which no one else did in their answers as of now? – Nahiyan Dec 28 '18 at 06:47