Search code examples
javascripthtmlundefinedrequirefs

I keep getting the error:require is not defined


<!DOCTYPE html>
<html lang="it">
  <title>Gamefic</title>
  <head>
   
    <link rel="stylesheet" href="style.css" type="text/css" />
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h1><strong><em>TEST</h1></em></strong>
    
    <input id= "text" type="text" value="" placeholder="Inserisci la tua idea qui"> <br> <br>
    <input id="button" type="button" onclick="c()" value = "premi questo pulsante">
    <button onclick="BB()">Test</button>
   <p id="b"></p>
  </body>
  <script src="script.js"></script>
  <script>   function BB(){ 
    var fs = require('fs') 
    fs.appendFile('IDEE.txt', 'Hello!', function(err, data){
        console.log(data)
    })}

    </script>
</html>

If somebody knows how to fix this problem or how to implement fs in HTML code I would appreciate it very much. I have tried almost everything. Thanks


Solution

  • require is not part of Javascript's standards. That part of code that you have, namely

    function BB(){ 
        var fs = require('fs') 
        fs.appendFile('IDEE.txt', 'Hello!', function(err, data){
            console.log(data)
        })
    }
    

    looks very much like NodeJS code that is to append some content to a file on your server's filesystem. However, this is only supported on your server, not in your browser. This might be confusing if you work on your machine and use a browser in the same machine, but don't think about this considering your special case as a developer. Instead, think about the users. Your server's code, the NodeJS will run a remote machine from the users' perspective, while that server will send out the web-page to their browser whose job is to display it.

    Now, browsers do not really allow file writing on users' file system in general, because in that case a malicious server could cause a lot of harm for the users. So, in order to avoid these dangers, file operations via the browser is very limited.

    The proper way to work with files is to develop some server-side code, in your case that would be Javascript under NodeJS, judging by your code and that server-side code should be triggered by a request sent by the user where a message would be sent. The server, on its turn would take that message and append to the file after proper validations, of course.