简体   繁体   中英

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.

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.

I want to write to the log file on my web server

JavaScript is a client side language; it runs on the computer running the browser not on the server. In order to update a log file on the server you'll need to eg perform an HTTP POST to send the data to some code on your server which will then save it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM