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



我想从使用node编写的React应用程序中运行另一个nodejs脚本。在这篇文章之前,我已经使用了我在这个论坛上找到的一种方法,来实现类似的事情,而且效果很好:https://stackoverflow.com/a/22649812/11340913.这是我的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;

这是我得到的错误:

TypeError:childProcess.fork不是函数

runScript
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,它在浏览器中提供了类似的功能。

相关内容

最新更新