[英]require('child_process').fork method “does not exist” in React app
I want to run another nodejs script from a React app I'm writing with node.我想从我用 node 编写的 React 应用程序运行另一个 nodejs 脚本。 I've already used before this post a method I found on this forum, to achieve a similar thing, and it worked just fine: https://stackoverflow.com/a/22649812/11340913 .在这篇文章之前,我已经使用了我在这个论坛上找到的一种方法,以实现类似的效果,并且效果很好: https://stackoverflow.com/a/22649812/11340913 。 This is my App.js fragment:这是我的 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;
This is the error I'm getting:这是我得到的错误:
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's child_process
module, like Node itself, runs in the backend (on the server) and so cannot be run in the browser which lacks access to the operating system in which child processes run. Node 的child_process
模块与 Node 本身一样,在后端(在服务器上)运行,因此无法在无法访问运行子进程的操作系统的浏览器中运行。 You might look into web workers
which provide similar functionality within the browser.您可能会查看在浏览器中提供类似功能的web workers
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.