【问题标题】:How to use filesystem (fs) in angular-cli with electron-js如何在 angular-cli 和 electron-js 中使用文件系统(fs)
【发布时间】:2017-03-21 15:55:29
【问题描述】:

我已经建立了一个 angular-cli 项目

(@Angular/cli: 1.0.0-rc.2 节点: 6.10.0 os: linux x64)

使用电子 js (v1.6.2) 而且我需要使用文件系统来创建/删除 .csv 文件和文件夹,但我不能包含在角度组件中

如何配置 angular-cli 以便能够: import fs from 'fs'?

【问题讨论】:

    标签: node.js electron angular-cli


    【解决方案1】:

    您不会将 Angular-CLI 配置为使用 NodeJS fs 模块。

    在电子中,您有 2 个进程;主要和渲染器。主进程控制诸如 browserWindow 之类的项目,它本质上是用户在打开他们的应用程序时看到的“窗口”,并反过来加载视图的 html 文件。在这里,在主进程中,您导入 fs 模块。

    在渲染过程中,您将处理来自视图的操作,并将它们发送到主进程。这是您将使用 IPC 通过事件进行通信以对主进程执行某些操作的地方。一旦该事件被触发,渲染进程将接收该事件并将其发送到 main。 Main 会用它做一些事情,例如在桌面上打开一个文件。

    我建议使用电子 API demo application 来查看清楚的示例。这是使用 FS 打印到 pdf 的示例(来自演示应用程序)。

    此外,这是 Ray Villalobos 使用 React 编写的电子application github 示例,其中包含一些类似的概念,将向您展示如何在应用程序中集成组件。

    渲染过程:

    const ipc = require('electron').ipcRenderer
    
    const printPDFBtn = document.getElementById('print-pdf')
    
    printPDFBtn.addEventListener('click', function (event) {
      ipc.send('print-to-pdf')
    })
    
    ipc.on('wrote-pdf', function (event, path) {
      const message = `Wrote PDF to: ${path}`
      document.getElementById('pdf-path').innerHTML = message
    })
    

    主进程:

    const fs = require('fs')
    const os = require('os')
    const path = require('path')
    const electron = require('electron')
    const BrowserWindow = electron.BrowserWindow
    const ipc = electron.ipcMain
    const shell = electron.shell
    
    ipc.on('print-to-pdf', function (event) {
      const pdfPath = path.join(os.tmpdir(), 'print.pdf')
      const win = BrowserWindow.fromWebContents(event.sender)
      // Use default printing options
      win.webContents.printToPDF({}, function (error, data) {
        if (error) throw error
        fs.writeFile(pdfPath, data, function (error) {
          if (error) {
            throw error
          }
          shell.openExternal('file://' + pdfPath)
          event.sender.send('wrote-pdf', pdfPath)
        })
      })
    })
    

    【讨论】:

    【解决方案2】:

    您可以尝试在组件中使用const fs = (<any>window).require("fs");,或者更好的是,创建一个 service.ts 提供程序来处理 i/o 操作。

    【讨论】:

      猜你喜欢
      • 2018-10-18
      • 2018-01-23
      • 1970-01-01
      • 2017-12-17
      • 2016-06-29
      • 1970-01-01
      • 2018-10-20
      • 2018-12-06
      • 1970-01-01
      相关资源
      最近更新 更多