Home > Software engineering >  How to console only one time in terminal if a function is called from http.createServer
How to console only one time in terminal if a function is called from http.createServer

Time:02-02

index.js file

import http from 'http';

function terminalConsole() {
  console.log(5);
}

const server = http.createServer((req, res) => {
  terminalConsole();
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello');
});

server.listen(5000, '127.0.0.1', () => {
  console.log(`server listening on localhost:5000`);
});

And when called from terminal, getting two 5 output instead of one. console Stackblitz link - https://stackblitz.com/edit/node-t5zngd?file=index.js

CodePudding user response:

You can use a function to log only once, based on the content of the log:

const logOnceClass = () => {
    const cache = new Map()
    return (string, logFunction = console.log) => {
        // if its already logged, return
        if (cache.has(string)) return 
        logFunction(string)
        cache.set(string, true)
    }

}

const logOnce = logOnceClass()

logOnce(1) // 1
logOnce(1) // (No log, "1" has been already logged)
logOnce(2) // 2

CodePudding user response:

Use req.on node.js event in-order to log to console on a specific event. Here is the fixed version of your code.

const http = require("http");

function terminalConsole() {
  console.log(5);
}

const server = http.createServer((req, res) => {
  res.setHeader("Content-Type", "text/plain");
  res.statusCode = 200;

  req.on('end', () => {
    terminalConsole();
  });

  res.end("Hello");
});

server.listen(3001, () => {
  console.log(`server listening on localhost:3001`);
});

What happens here is that every time a request has been end, it would log the message to console.

  •  Tags:  
  • Related