How can I access file system from an external javascript file?

933 views Asked by At

I have a file named server.js which reads an HTML file named "game.html".

That HTML file is linked with an external javascript file named "game.js".

In server.js file

if(request.url.indexOf('.html') != -1) {
    fs.readFile("game" + request.url, function (error, data) {
        if (error) {
            response.writeHead(404, {"COntent-type":"text/plain"});
            response.end("No Html Page Found.");
        } else{
            response.writeHead(200, {'Content-Type': 'text/html'});
            response.write(data);
            response.end(); 
        }

     });
}
else if(request.url.indexOf('.js') != -1) {
        fs.readFile("game" + request.url, function (error, data) {
            if (error) {
                response.writeHead(404, {"COntent-type":"text/plain"});
                response.end("No Javascript Page Found.");
            } else{
                response.writeHead(200, {'Content-Type': 'text/javascript'});
                response.write(data);
                response.end(); 
            }

        });
    }

In game.html file

<script src="game.js">

In game.js file

function loadXMLDoc(update) {
var fs = require('fs');

if(update)
{
    //Write
    fs.writeFileSync("highscore.txt", s);   
}
else
{
    //Read
    console.log("Reading Highscore.");
    var highscore = fs.readFileSync("highscore.txt");
    console.log("Saved Highscore : " + highscore);
    console.log("Finished Reading.");
}

}

I always get this error while using "var fs = require('fs')" in game.js.

ReferenceError: require is not defined

Any solution to this problem ?

0

There are 0 answers