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

岁酱吖の 提交于 2019-12-07 10:45:29

问题


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!


回答1:


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!




回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/47883109/how-can-i-use-node-fs-in-electron-within-angular-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!