Search code examples
javascriptbrowserifyfs

Why doesn't Browserify work with fs.readFileSync?


When I run my code:

var fs = require('fs');
var text = fs.readFileSync('data.txt').toString().split("\n");

function getDataJS(){
    var i = 0;
    var c = "";
    var d = "";
    var t = "";
    var r = "";
    for(i = 0;i<text.length;i++){
        if(i == 0){
            c = text[i];
            document.getElementById('con').innerHTML = c;
        } else if(i == 1){
            d = text[i]
            document.getElementById('dec').innerHTML = d;
        } else if(i == 2){
            t = text[i]
            document.getElementById('tes').innerHTML = t;
        } else if(i == 3){
            r = text[i]
            document.getElementById('rec').innerHTML = r;
        }
    }
}


module.exports = getDataJS();

(with my html) I get:

Uncaught TypeError: fs.readFileSync is not a function

Does anyone know why this is? I know that node does not work with browsers, but I'm confused why browserify isn't working.


Solution

  • From Browserify:

    Browsers don't have the require method defined, but Node.js does. With Browserify you can write code that uses require in the same way that you would use it in Node.


    Browserify let's you use require. It doesn't let you use the APIs provided by Node.js that are not provided by browsers… including those needed to read files from the computer the code is running on.