How can I use node “fs” in electron within angular

2019-05-08 06:09发布

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!

3条回答
乱世女痞
2楼-- · 2019-05-08 06:42

Your browser cannot access the file system on the server. fs should not be loaded in the browser

查看更多
戒情不戒烟
3楼-- · 2019-05-08 06:49

I found the answer with the help of the comments from kimy82!

First i needed to get the Angular5 webpack.config.js by simply using:

ng eject

After that i opened up the webpack.config.js and added the following:

"target": "node-webkit"

Simply "node" did not work out for me and since electron uses a Chromium this should be ok.

Thanks everyone!

查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-05-08 06:53

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');
}
查看更多
登录 后发表回答