Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

351
Vistas
nodejs: cómo esperar el inicio del servidor en http://localhost:8000

Estoy iniciando el servidor desde mi script y luego quiero ejecutar mis pruebas. Pero cuando inicio el servidor, el proceso de inicio del servidor no regresa, ya que se está ejecutando y el control no se devuelve. El servidor se inicia y se puede acceder a la aplicación en http://localhost:8000. así que he usado la búsqueda de nodejs y la solicitud http para verificar si la respuesta == 200 en http://localhost:8000 pero obtengo el error: console.error FetchError {mensaje: 'solicitud a http://127.0.0.1:8000/ falló, razón: conecte ECONNREFUSED 127.0.0.1:8000', escriba: 'sistema', errno: 'ECONNREFUSED', código: 'ECONNREFUSED' } ¿Hay alguna manera de que pueda sondear y comenzar mis pruebas? Mi código:

 const util = require('util'); const exec = util.promisify(require('child_process').exec); const fetch = require('node-fetch'); const http = require('http'); async function waitforlocalhost() {    await fetch('http://127.0.0.1:8000/'), (response) => {    //http.get({hostname:'localhost',port: 8000,path: '/',method: 'GET',agent: false}, (response) => {    if (response.status === 200) {        resolve();        return;    } else {        setTimeout(waitforlocalhost,2000);    } } } class CreateEnv {    async  Execute () {        try {            //create database and start server            console.log("Create database and runserver...");            exec('python manage.py startserver');            await waitforlocalhost();            console.log("Server started...");        } catch (e) {            console.error(e);            console.log("Error creating database and runserver...");            return;        }    } } module.exports = CreateEnv;
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Reescribió su corrector de la siguiente manera,

  • bucle x veces con un bucle while
  • antes de cada comprobación, dormir durante x milisegundos
  • si es bueno resolver prometer
  • si no, rechazar
  • catch stop u otro error en el intento externo/captura

 const fetch = require('node-fetch') function waitforhost(url, interval = 1000, attempts = 10) { const sleep = ms => new Promise(r => setTimeout(r, ms)) let count = 1 return new Promise(async (resolve, reject) => { while (count < attempts) { await sleep(interval) try { const response = await fetch(url) if (response.ok) { if (response.status === 200) { resolve() break } } else { count++ } } catch { count++ console.log(`Still down, trying ${count} of ${attempts}`) } } reject(new Error(`Server is down: ${count} attempts tried`)) }) } async function main() { const url = 'http://127.0.0.1:8000/' console.log(`Checking if server is up: ${url}`) try { await waitforhost(url, 2000, 10) console.log(`Server is up: ${url}`) } catch (err) { console.log(err.message) } } main()

Resultados en:

 Checking if server is up: http://127.0.0.1:8000/ Still down, trying 2 of 10 Still down, trying 3 of 10 Still down, trying 4 of 10 Still down, trying 5 of 10 Still down, trying 6 of 10 Still down, trying 7 of 10 Still down, trying 8 of 10 Still down, trying 9 of 10 Still down, trying 10 of 10 Server is down: 10 attempts tried

O cuando el éxito

 Checking if server is up: http://127.0.0.1:8000/ Server is up: http://127.0.0.1:8000/

Te dejaré implantar en tu código.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda