Остановите nodejs child_process с помощью вызова API браузера - PullRequest
0 голосов
/ 02 февраля 2019

У меня есть vue (axios), выполняющий вызов get для экспресс-маршрута, который запускает child_process ffmpeg в бесконечном цикле.ffmpeg передает один файл через udp, при закрытии он вызывает сам себя и передает другой файл.

Я хотел бы иметь возможность убить этот процесс с помощью кнопки на веб-странице, но, похоже, не работаетэто вне.

Это мой код экспресс-маршрута

router.get('/test', function(req, res) {
  const childProcess = require('child_process');
  const fs = require('fs')
  const path = require('path')

  //Grabs a random index between 0 and length
  function randomIndex(length) {
    return Math.floor(Math.random() * (length));
  }
  function Stream () {
  const FILE_SRC =  '/path/to/file'
  //Read the directory and get the files
  const dirs = fs.readdirSync(FILE_SRC)
    .map(file => {
      return path.join(FILE_SRC, file);
    });

  const srcs_dup = [];
  const hashCheck = {}; //used to check if the file was already added to srcs_dup
  var numberOfFiles = dirs.length - 1; //OR whatever # you want

  console.log(numberOfFiles)

  //While we haven't got the number of files we want. Loop.
  while (srcs_dup.length < numberOfFiles) {
    var fileIndex = randomIndex(dirs.length-1);

    //Check if the file was already added to the array
    if (hashCheck[fileIndex] == true) {
      continue; //Already have that file. Skip it
    }

    //Add the file to the array and object
    srcs_dup.push(dirs[fileIndex]);
    hashCheck[fileIndex] = true;
  }
  var chosen = "'" + srcs_dup[0] + "'"

  var call = "ffmpeg -re -i " + chosen + " -content_type audio/mpeg -f mp3 udp://224.1.2.3:1234"

  const stop = childProcess.exec(call, { shell: true });

  stop.stdout.on('data', function (data) {
    console.log('stdout: ' + data.toString());
  });

  stop.stderr.on('data', (data) => {
    console.log(`stderr: ${data}`);
  });

  stop.on('close', (code) => {
    console.log ('child exited with code ' + code)
    Stream();
  });

  stop.on('error', function(err) {
    console.log('sh error' + err)
  });
  }
...