Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use node "fs" in electron within angular 5

Tags:

I try to use Electron and Angular5 to write my first desktop App but unfortunately i am stuck in using the fs module. It seems that I have imported fs correctly (no errors within Visual Studio Code and code completion) but when i tried using "fs.readFile" the console prints out this error:

Uncaught TypeError: __WEBPACK_IMPORTED_MODULE_2_fs__.readFile is not a function

This is the code of my service so far:

import { Injectable } from '@angular/core';
import { ElectronService } from 'ngx-electron';
import * as fs from 'fs';
import { OpenDialogOptions } from 'electron';

@Injectable()
export class FileService {

  dialog = this._electronService.remote.dialog;
  window = this._electronService.remote.getCurrentWindow();

  constructor(private _electronService: ElectronService) { }

  loadFileContent(): void{
    this.dialog.showOpenDialog(this.window, {},(fileNames) => {
      if(fileNames === undefined){
        console.error("no files selected!");
        return;
      }

      fs.readFile(fileNames[0], "utf-8", (err, data) => {
        if(err){
          console.error("Cannot read file ",err);
          return;
        }

        console.log("The content of the file is : ");
        console.log(data);
      });

    });
  }
}

Do I miss something here? Seems that fs is not loaded or something? Thanks for your help everyone!

like image 698
sonnenpriester Avatar asked Dec 19 '17 08:12

sonnenpriester


1 Answers

You can also use remote.require to load native node modules from ngx-electron.

fs;

constructor(private _electronService: ElectronService) { 
    this.fs = this._electronService.remote.require('fs');
}
like image 66
Ben Burnett Avatar answered Sep 23 '22 12:09

Ben Burnett