Search code examples
reactjsnwjs

how to use nodejs modules in nw/react app


I'm trying to build an app with NW ans react and i'm having trouble calling node js modules fron react like the "fs" module i got the following error: TypeError: fs.readdir is not a function

this is my folders structure:

public
-----files generated by CRA
src
-----main.js
-----handlers.js
-----files generated by 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;



Solution

  • Add this to your package.json:

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

    You may also need this:

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