[英]require('child_process').fork method “does not exist” in React app
我想從我用 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;
這是我得到的錯誤:
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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.