简体   繁体   English

无法在 electron.js 应用程序的 main.js 文件中加载 node.js 模块

[英]Can't load node.js module in main.js file of electron.js application

I've been building electron app and main.js file became to big so I desided to split it into modules.我一直在构建 electron 应用程序并且 main.js 文件变得很大,所以我决定将其拆分为模块。 But some modules don't load and stop following modules from loading.但是某些模块不会加载并停止加载后续模块。 I need to find out the source of this problem.我需要找出这个问题的根源。 To load modules I use the following system:要加载模块,我使用以下系统:

const createWindow = () => {
  mainWindow = new BrowserWindow({
    ...options
  });

  requireModules();
};

app.on('ready', createWindow);

// Load modules after mainWindow created
const requireModules = () => {
  require('./modulesMain/open')(mainWindow);
  require('./modulesMain/watchers')(mainWindow);

  require('./modulesMain/testModule')(mainWindow);
};

Modules after require('./modulesMain/watchers')(mainWindow); require('./modulesMain/watchers')(mainWindow);之后的模块don't load.不要加载。 Module watchers' code:模块watchers'代码:

const electron = require('electron');
const { ipcMain } = electron;
const chokidar = require('chokidar');

const { transfPathForWin } = require('./helpersMain/helpers');

let watchedArray = [];

module.exports = (mainWindow) => {
  ipcMain.on('start-watching-dir', (event, dirPath, tabId) => {
    const perviouslyThisTab = watchedArray.find((item) => item.id === tabId);

    if (perviouslyThisTab) {
      perviouslyThisTab.watcher.close();
    }

    watchedArray = watchedArray.filter((item) => item.id !== tabId);
    try {
        const winDirPath = transfPathForWin(dirPath);

        const watcher = chokidar.watch(winDirPath, {
          persistent: true,
          ignored: '*.sys',
          ignoreInitial: true,
          followSymlinks: true,
          cwd: '.',
          disableGlobbing: false,
          usePolling: false,
          interval: 100,
          binaryInterval: 300,
          alwaysStat: false,
          depth: 0,
          awaitWriteFinish: {
            stabilityThreshold: 2000,
            pollInterval: 100,
          },
          ignorePermissionErrors: false,
          atomic: true,
        });

        // Add event listeners.
        watcher
          .on('add', (path) => {
            console.log(`File ${path} has been added`);
            mainWindow.webContents.send('refresh-tab', { tabId, dirPath });
          })
          .on('change', (path) => {
            console.log(`File ${path} has been changed`);
            mainWindow.webContents.send('refresh-tab', { tabId, dirPath });
          })
          .on('unlink', (path) => {
            console.log(`File ${path} has been removed`);
            mainWindow.webContents.send('refresh-tab', { tabId, dirPath });
          })
          .on('ready', () =>
            console.log('Initial scan complete. Ready for changes')
          )
          .on('addDir', (path) => {
            if (path === '..\\..\\..') return;
            console.log(`Directory ${path} has been added`);
            mainWindow.webContents.send('refresh-tab', { tabId, dirPath });
          })
         .on('unlinkDir', (path) => {
           if (path === '..\\..\\..') return;
           console.log(`Directory ${path} has been removed`);
           mainWindow.webContents.send('refresh-tab', { tabId, dirPath });
         });

        watchedArray.push({ id: tabId, path: dirPath, watcher });
    } catch (err) {
      // error watching - no access or something
    }
  });

  ipcMain.on('stop-watching-dir', (event, dirPath, tabId) => {
    const watchedItem = watchedArray.find((item) => item.id === tabId);

    try {
      watchedItem.watcher.close();

      watchedArray = watchedArray.filter((item) => item.id !== tabId);
    } catch (err) {
      // error watching - no access or something
    }
  });

  ipcMain.on('stop-watching-all', (event) => {
    watchedArray.map((item) => item.watcher.close());
    watchedArray = [];
  });

  ipcMain.on('close-tabs', (event, data) => {
    const { excludedTabs } = data;
    watchedArray = watchedArray.filter((item) => {
      if (excludedTabs.includes(item.id)) {
        return true;
      } else {
        item.watcher.close();
        return false;
      }
    });

    console.log('watchedArray', watchedArray);
  });
};

I found the error: it was incorrect import const { transfPathForWin } = require('./helpersMain/helpers');我发现了错误:它不正确 import const { transfPathForWin } = require('./helpersMain/helpers'); instead should be const { transfPathForWin } = require('../helpersMain/helpers');相反应该是const { transfPathForWin } = require('../helpersMain/helpers'); which caused path convertion error, which caused app crash.这导致路径转换错误,导致应用程序崩溃。 In addition I forgot to add console.log(err) in catch instruction, so chokidar crashed silently.另外我忘了在catch指令中添加console.log(err) ,所以chokidar默默地崩溃了。 The reason for following modules not to load was that module exported using function module.exports = (mainWindow) => {...code} , which crushed and that stopped requireModules function from continuing its execution and loading following modules以下模块不加载的原因是使用 function module.exports = (mainWindow) => {...code}导出的模块,它崩溃并停止了requireModules function 继续执行和加载以下模块

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM