Reputation: 99
I get this error in the browser when I run my .html file
Uncaught ReferenceError: require is not defined
My File_system.html is:
<!DOCTYPE html>
<html>
<head>
<title>window.requestFileSystem problem</title>
<script type="text/javascript" src="server.js"></script>
<script>
function onInitFs(fs) {
console.log(fs);
console.log(fs.getDirectory());
}
function errorHandler(e) {
var msg = '';
console.log(e);
switch (e.code) {
case FileError.QUOTA_EXCEEDED_ERR:
msg = 'QUOTA_EXCEEDED_ERR';
break;
case FileError.NOT_FOUND_ERR:
msg = 'NOT_FOUND_ERR';
break;
case FileError.SECURITY_ERR:
msg = 'SECURITY_ERR';
break;
case FileError.INVALID_MODIFICATION_ERR:
msg = 'INVALID_MODIFICATION_ERR';
break;
case FileError.INVALID_STATE_ERR:
msg = 'INVALID_STATE_ERR';
break;
default:
msg = 'Unknown Error';
break;
};
console.log('Error: ' + msg);
}
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.PERSISTENT, 1024*1024,onInitFs,errorHandler);
</script>
</head>
<body>
</body>
</html>
And my server.js file is:
var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('File_system.html');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(index);
}).listen(8080);
What is wrong with this? Please help
I should be able to retrieve all the fs methods in the console and create a directory with tat. But I am stuck in this. Or is there any way to directly run in browser?
Upvotes: 3
Views: 59925
Reputation: 73044
Edit: Rereading your original post, it's possible that you are in fact running this Node.js script in a Node environment, trying to use fs
to load your .html file. If that's the case, you are calling your Node server.js script within your .html file like so:
<script type="text/javascript" src="server.js"></script>
Simply remove this line, and you should no longer receive the error you're seeing.
As previously stated, you're attempting to implement Node.js code in your client-side script. In theory this can be done, but isn't recommended, and Node.js simply isn't designed for this purpose (it's a server!)
You should be using XHR/ajax
to make http requests from your client to a server (not fs
), and then handle those things on the back end. This can be done easily with a conventional web stack like Apache and php, or if you really want to use fs
, run an API off of Node.js and connect your client to it using XHR/ajax
, or implement an MVC stack like Sails.js.
Upvotes: 4
Reputation: 160963
server.js
should run in the server side (which has nodejs be installed).
Upvotes: 2
Reputation: 1857
You can't use your node.js script in browser. Only run it with node.js.
Upvotes: 3