Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use filesystem (fs) in angular-cli with electron-js

I have set up an angular-cli project

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

With electron js (v1.6.2) And I need to use the filesystem to create / delete .csv files and folders, but I can not do includ in the angular component

How could you configure the angular-cli to be able to: import fs from 'fs'?

like image 268
Vladimir J. Castañeda G. Avatar asked Mar 21 '17 15:03

Vladimir J. Castañeda G.


1 Answers

You wouldn't configure Angular-CLI to use the NodeJS fs module.

In electron you have 2 processes; main and renderer. The main process controls items such as the browserWindow, which is essentially the 'window' the user sees when they open their app, and in turn this loads the html file for the view. Here, in the main process, you import the fs module.

In the render process, you would handle actions from the view, and send them to the main process. This is where you would use IPC to communicate via events to do something with the main process. Once that event is triggered, the render process takes the event and sends it to main. Main would do something with it, and open a file for example on the desktop.

I would recommend using the electron API demo application to see clear examples of this. Here is an example of print to pdf using FS (from the demo app).

Also, here is an electron application github example written by Ray Villalobos using React, which has some similar concepts that will show you how to integrate components in your app.

Render process:

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
})

Main Process:

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)
    })
  })
})
like image 164
unseen_damage Avatar answered Sep 22 '22 13:09

unseen_damage