使用浏览器API调用停止Node.js child_process

时间:2019-02-02 14:37:26

标签: node.js express kill child-process

我让Vue(axios)调用一条Express路由的get路由,该路由在无限循环中触发ffmpeg的child_process。 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)
  });
  }

0 个答案:

没有答案