Почему порожденный дочерний процесс в событии огня закрывается даже перед выполнением? - PullRequest
0 голосов
/ 03 июля 2019

Я создаю инструмент, который выполняет сценарии кукловода из файла JSON.Задача здесь состоит в том, чтобы реализовать параллельную обработку для имитации множества браузеров, которая выполняется путем передачи userAgent, height и width в экземпляр puppeteer.

Однако при порождении дочерних процессов они запускают событие close с кодом 1без выполнения даже одной строки в compute.js.

Ответы и предложения приветствуются.

Файл index.js

const {spawn} = require('child_process');
const browserConfig = require('../config/browser-config');

// command for reference mode : npm start ref/test login 
//var mode = process.argv[2];

var testScriptName = process.argv[2];
var testScriptPath;
var testScript;
var browserList;

if (testScriptName) {
  console.log(testScriptName, '<------test-script');
  testScriptPath = './test-scripts/' + testScriptName;
  console.log(testScriptPath, '<------path');
  testScript = require(testScriptPath);
  browserList = testScript.start.browserList;
  console.log(`browserlist --> ${browserList}`);
}

browserList.forEach(function (browser){
  console.log(`browser-> ${browser}`);
  let childProcess = spawn('node', ['./workers/compute.js', testScriptName, browserConfig[browser]]);
  childProcess.on('close', function(code){
    console.log(`Child process exited with code --> ${code}`);
  });
  childProcess.on('error', function(code){
    console.log(`Child process errord with code --> ${code}`);
  });
  childProcess.on('disconnect', function(code){
    console.log(`Child process disconnect with code --> ${code}`);
  });
  childProcess.on('message', function(message){
    console.log(`Child process message --> ${message.value}`);
  });
});

Файл src / worker / compute.js

process.send({value: 'messsssssss'});

var testScriptName = process.argv[2];
var testScriptPath = './test-scripts/' + testScriptName;
var hostEnv = process.argv[3];
var puppeteer = require('puppeteer');

console.log(`Inside test script for hostEnv ----->${hostEnv}`);

var testScript = require(testScriptPath);
var screenCapture = require('./screenCapture.js');

var imageCounter = 0;


async function rollout(hostEnv) {
  const width = hostEnv.width;
  const height = hostEnv.height;

  const browser = await puppeteer.launch({
    headless: false,
    args: [
      `--window-size=${width},${height}`
    ],
  });

  const page = await browser.newPage();
  await page.setUserAgent(hostEnv.userAgent);
  await page.setViewport({ width, height });

  return { browser, page };
}

async function boost(page, browser) {
  var configObj = testScript;
  var startUrl = configObj.start.open;
  await page.goto(startUrl, { "waitUntil": "networkidle0" });
  await screenCapture.captureImage(page, '../../capturedImages/' + testScriptName + '/' + imageCounter + '.png');
  imageCounter++;
  await processArray(configObj.then, page, browser);
}

async function processArray(array, page, browser) {
  for (const item of array) {
    await executeStep(item, page);
  }
  await browser.close();
}

async function executeStep(element, page) {
  if (element.inputAction === 'text') {
    await page.type(element.inputElement, element.inputValue, { delay: 50 });
  } else if (element.inputAction === 'click') {
    console.log('clicking on ', element.inputElement);
    await page.click(element.inputElement);
  }
  if (element.waitFor) {
    await page.waitForSelector(element.waitFor);
  }

  if (element.screenShotArea.length > 0) {
    var div = element.screenShotArea[0];
    await screenCapture.captureImage(page, '../../capturedImages/' + testScriptName + '/' + imageCounter + '.png', div);
    imageCounter++;
  }
  console.log('.....................')
}

var {page, browser} = rollout(testScriptPath, hostEnv);
boost(page, browser);

Индексный файлпорождает несколько новых child_processes, но все процессы закрываются с кодом один, и все, что я получаю, это если массив browserList имеет 3 элемента:

Child process exited with code --> 1
Child process exited with code --> 1
Child process exited with code --> 1

Требуемый результат здесь: код compute.js должен выполняться параллельно дляразные браузеры.

1 Ответ

0 голосов
/ 09 июля 2019

Проблема заключалась в том, что мой родительский процесс узла закрывал пост, порождая дочерние процессы, так как ему больше нечего было делать. Закрытие родительского процесса также привело к закрытию дочерних процессов без выполнения какой-либо работы, которую они должны были выполнить.

Выше приведена причина получения:

Child process exited with code --> 1
Child process exited with code --> 1
Child process exited with code --> 1
...