nodejs:如何等待服务器在 http://localhost:8000 启动

nodejs: How to wait for server start at http://localhost:8000

我正在从我的脚本启动服务器,然后想执行我的测试。但是当我启动服务器时,服务器启动进程不会 return 因为它是 运行 并且控制不会 return 返回。服务器启动,可以在 http://localhost:8000 上访问应用程序。 所以我使用 nodejs fetch 和 http request 来检查 http://localhost:8000 处的 response==200 是否存在,但出现错误: console.error 获取错误{ 消息:'request to http://127.0.0.1:8000/ failed, reason: connect ECONNREFUSED 127.0.0.1:8000', 类型:'system', 错误号:'ECONNREFUSED', 代码:'ECONNREFUSED' } 有什么办法可以轮询并开始我的测试吗? 我的代码:

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;

像下面这样重写你的检查器,

  • 用 while 循环循环 x 次
  • 在每次检查之前,休眠 x 毫秒
  • 如果好,解决承诺
  • 如果没有,拒绝
  • 在外部捕获停止或其他错误 try/catch

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()

结果:

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

或成功时

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

我会留给你植入你的代码。