如何在 nw/react 应用程序中使用 nodejs 模块

how to use nodejs modules in nw/react app

我正在尝试使用 NW ans react 构建一个应用程序,但我在调用节点 js 模块时遇到了问题,就像“fs”模块一样,我收到以下错误:TypeError:fs.readdir 不是函数

这是我的文件夹结构:

public
-----CRA生成的文件
来源
-----main.js
-----handlers.js
-----CRA生成的文件

package.json

{
  "name": "nw-react",
  "version": "0.1.0",
  "private": true,
  "main": "./public/main.js",
  "dependencies": {
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3",
    "web-vitals": "^1.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "nw" : "nw ."
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "cross-env": "^7.0.3",
    "nw": "^0.64.1"
  }
}

main.js

nw.Window.open("http://localhost:3000", {}, function (win) {});

handlers.js

const fs = require("fs");

exports.getFiles = cb => {
  const dir = "C:\Users\pc\Documents";
  fs.readdir(dir, (err, files) => {
    cb(files);
  });
};

App.js

import { useState, useEffect } from "react";
import logo from "./logo.svg";
import "./App.css";

const handlers = require("./handler");

function App() {
  const [files, setFiles] = useState([]);
  useEffect(() => {
    handlers.getFiles(files => {
      setFiles(files);
    });
  }, []);

  return (
    <div className='App'>
      {files.map(file => (
        <h1 key={file}>{file}</h1>
      ))}
    </div>
  );
}

export default App;


您不能在浏览器中使用 fs 模块。它是节点核心模块。

将此添加到您的 package.json:

  "node-remote": [
    "http://localhost:3000",
    "file://*"
  ]

您可能还需要这个:

  "eslintConfig": {
    "extends": "react-app",
    "globals": {
      "nw": true
    }
  }