Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

198
Views
How to console only one time in terminal if a function is called from http.createServer

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!