First I dowloaded nodejs from link.
Then I installed browserify npm install -g browserify
Then I installed fs npm install fs
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
const fs = require('fs');
fs.writeFile("/tmp/test", "Hey there!", function(err) {
if(err) {return console.log(err);}
console.log("The file was saved!");
});
</script>
</body>
</html>
I am getting the following error:
Uncaught ReferenceError: require is not defined
at index.html:12:12
Why require is still not defined? What could I do to get the code to be executable?
CodePudding user response:
Node.js is a stand-alone environment for running JavaScript. It is not a browser extension.
To run Node.js code, save it in a file with a .js
file extension, then run it with:
node yourFile.js
If you want Node.js code and browser code to interact then the typical way is to write a server in Node.js that hosts a web service. Express.js is a popular way to do this. You can then use Ajax to make HTTP requests to that web service.
For bi-directional communication (as opposed to the request/response of Ajax) look at Socket.io.
I just want it to be local storage, so I do not want to share the datas between the users, I just want to interact with there own local storage datas.
If you want to use the localStorage API provided by browsers, then do so.
localStorage
doesn't need Node.js. It doesn't need the fs
module that is built into Node.js. It doesn't need the require
method that is part of the CommonJS module specification.
You can't muck around freely on the user's file system from code running in the browser. That would be a huge security problem.
CodePudding user response:
You can't use node APIs in browser environment; more specifically browser won't allow script to directly interact with file APIs like Node.
Either run your code in node as quentin said, or use browser file api