React 应用程序中的 require('child_process').fork 方法 "does not exist"

require('child_process').fork method "does not exist" in React app

我想 运行 我正在用 node 编写的 React 应用程序中的另一个 nodejs 脚本。在此之前,我已经使用 post 我在该论坛上找到的一种方法来实现类似的目的,并且效果很好:。这是我的 App.js 片段:

import React from 'react';
import Peer from 'peerjs';

const childProcess = require('child_process');

function runScript(scriptPath, callback) {

    // keep track of whether callback has been invoked to prevent multiple invocations
    let invoked = false;

    let process = childProcess.fork(scriptPath);

    // listen for errors as they may prevent the exit event from firing
    process.on('error', err => {
        if (invoked) return;
        invoked = true;
        callback(err);
    });

    // execute the callback once the process has finished running
    process.on('exit', code => {
        if (invoked) return;
        invoked = true;
        var err = code === 0 ? null : new Error('exit code ' + code);
        callback(err);
    });

}

// Now we can run a script and invoke a callback when complete, e.g.
runScript('./node_modules/peer/bin/peerjs', err => {
    if (err) throw err;
    console.log('started p2p server!');
});

const peer = new Peer('banana_nebuna123' ,{
  key: 'peerjs',
  port: 9000,
  host: '127.0.0.1',
  secure: false,
  //path: '/home/eugen/Documents/scripts/ReactProjects/ShareLife/node_modules/peer/bin/peerjs'
}); 

function App() {
  
  return (
    <>
      <h1>
        hello, world!
      </h1>
    </>
  );
}

export default App;

这是我遇到的错误:

类型错误:childProcess.fork 不是函数

运行脚本
src/App.js:11

   8 | // keep track of whether callback has been invoked to prevent multiple invocations
   9 | let invoked = false;
  10 | 
> 11 | let process = childProcess.fork(scriptPath);
     | ^  12 | 
  13 | // listen for errors as they may prevent the exit event from firing
  14 | process.on('error', err => {

Node 的 child_process 模块,就像 Node 本身一样,运行 位于后端(在服务器上),因此不能 运行 在无法访问操作系统的浏览器中其中子进程 运行。您可能会查看在浏览器中提供类似功能的 web workers