Home > Software engineering >  How to display on the page the data that was displayed in the console
How to display on the page the data that was displayed in the console

Time:12-06

In a small application made with Express.js, I print text to the console every second and after 4 seconds I stop the text output to the console. I need to return the current date to the page after the input to the console has expired. How can I do this?

var express = require("express");
var app = express();

app.get("/", (req, res) => {
  function outputText() {
     console.log("Some text");
  }
  const interval = setInterval(outputDate, 100);
  setTimeout(() => {
    clearInterval(interval);
  }, 4000);
  res.send();
});

app.listen(3000);

CodePudding user response:

To display text on a web page, you can use the res.send() method. This method can be used to send a string or HTML as a response to the client's request.

Here is an example of how you can modify your code to display the text on the page:

var express = require("express");
var app = express();

app.get("/", (req, res) => {
  function outputText() {
    console.log("Some text");
    // Use res.send() to send the text to the client
    res.send("Some text");
  }
  const interval = setInterval(outputDate, 100);
  setTimeout(() => {
    clearInterval(interval);
  }, 4000);
});

app.listen(3000);

This code will send the text "Some text" to the client every 100 milliseconds for 4 seconds. The text will be displayed on the page.

Note: You may want to use the res.write() method instead of res.send() if you want to send multiple strings as the response. res.write() will write the string to the response without ending the response, so you can call it multiple times to send multiple strings. You will need to call res.end() at the end to end the response.

Here is an example of how you can use res.write() and res.end() to display text on the page:

var express = require("express");
var app = express();

app.get("/", (req, res) => {
  function outputText() {
    console.log("Some text");
    // Use res.write() to write the text to the response
    res.write("Some text");
  }
  const interval = setInterval(outputDate, 100);
  setTimeout(() => {
    // Use res.end() to end the response
    res.end();
    clearInterval(interval);
  }, 4000);
});

app.listen(3000);

This code will have the same effect as the previous example. It will send the text "Some text" to the client every 100 milliseconds for 4 seconds, and the text will be displayed on the page.

  • Related