【问题标题】:How programmably wait until the process will start the endpoint如何以可编程方式等待进程启动端点
【发布时间】:2019-04-24 15:14:38
【问题描述】:

我在 node.js 中创建了一个small example application,这里有单元测试和验收测试

单元测试和验收测试都在 mocha 进程中运行。验收测试从分叉进程开始,基本上在 before() 方法上运行服务器。 after() 方法停止进程并

before((initialized) => {
  console.log('before script');
  serverProcess = child_process.fork('server.js');
  serverProcess.on('close', function (code) {  
  console.log('child process exited with code ' + code);  
});
setTimeout(() => {
  console.log('1s elapsed');
  initialized();
}, 1000);

没有任何延迟的代码在我的本地 gitlab-runner 上运行,但是在服务器上并非总是如此,所以我添加了延迟 - 等待一段时间,直到服务器启动。 根据经验,我发现 1s 就足够了,而 0.5s 则不够。 但是,我想知道我应该怎么做才能确保服务器正常。

Are there any solutions to run server, execute the tests and shutdown the server that works on Linux, Windows, docker and outside of it?

【问题讨论】:

    标签: node.js process timeout delay


    【解决方案1】:

    关于how to communicate between fork processes有很好的帮助。

    这个想法是让孩子向它的父亲发送一条消息(我准备好了!)。然后爸爸会继续工作。

    示例:

    before((initialized) => {
      serverProcess = child_process.fork('server.js');
    
      serverProcess.on('close', function(code) {
        console.log('child process exited with code ' + code);
      });
    
      serverProcess.on('close', function(code) {
        console.log('child process exited with code ' + code);
      });
    
      // We add a backup plan. If it takes too long to launch, throw
      const timeout = setTimeout(() => {
        initialized(new Error('tiemout');
      }, 30000);
    
      // Cait for the child to send a message to us
      serverProcess.on('message', function(str) {
        if (str === 'init done') {
          clearTimeout(timeout);
    
          // server.js got successfully initialized
          initialized();
        }
      });
    });
    

    // To add inside of your server.js listen
    if (process.send) {
      process.send("init done");
    }
    

    【讨论】:

      猜你喜欢
      • 2019-09-25
      • 1970-01-01
      • 1970-01-01
      • 2013-10-20
      • 1970-01-01
      • 2011-06-18
      • 1970-01-01
      • 1970-01-01
      • 2013-12-31
      相关资源
      最近更新 更多