Skip to content
Advertisement

How to save logs to a text file using JavaScript

I am making a website, and I have Javascript code located directly in the HTML with the script tags. I want to log the IP addresses to a blank text file located in log/logfile.txt. I have a script to capture the time and IP address of the user, and here it is:

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   <script>
       $.get("https://ipinfo.io", function(response) {
           var ip = response.ip
       }, "json")
       var today = new Date();
       var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
       var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
       var dateTime = date+' '+time;
       var data = response.ip+' Connected at '+dateTime;
       </script>

I want to write to the log file on my web server, but I don’t know how. I’ve looked for similar question here but have found no answer. I’ve tried

const fs = require('fs') 

fs.writeFile('log/logfile.txt', data, (err) => { 
      
    if (err) throw err; 
}) 

And again, it doesn’t work. Any help resolving this problem would be greatly apreciated.

Advertisement

Answer

JavaScript running in the browser cannot write to files on the server.

You need to send data to the server (typically this would be done by making an HTTP request; you’re using jQuery already so you could use $.post for this).

Then you need to read the data from the request using server-side code and write it to the file. The code you’ve found is designed to run using Node.js. You could write a web server using Node.js (the Express.js framework is helpful for this) to handle this. If you don’t want to use server-side JS (or if your web hosting only provides you with other programming language support) you can use any other language for the server-side portion of the program.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement