【问题标题】:How can I use node "fs" in electron within angular 5如何在角度 5 内的电子中使用节点“fs”
【发布时间】:2018-06-01 15:51:04
【问题描述】:

我尝试使用 Electron 和 Angular5 编写我的第一个桌面应用程序,但不幸的是我被困在使用 fs 模块。似乎我已经正确导入了 fs(Visual Studio Code 和代码完成中没有错误)但是当我尝试使用“fs.readFile”时,控制台会打印出这个错误:

Uncaught TypeError: __WEBPACK_IMPORTED_MODULE_2_fs__.readFile is not a function

这是我目前服务的代码:

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

    });
  }
}

我在这里错过了什么吗?似乎 fs 没有加载或什么?感谢大家的帮助!

【问题讨论】:

    标签: node.js angular typescript electron


    【解决方案1】:

    我在 kimy82 的 cmets 的帮助下找到了答案!

    首先我需要通过简单地使用来获取 Angular5 webpack.config.js:

    ng eject
    

    之后我打开了 webpack.config.js 并添加了以下内容:

    "target": "node-webkit"
    

    简单的“节点”对我来说不起作用,因为电子使用铬,这应该没问题。

    谢谢大家!

    【讨论】:

    【解决方案2】:

    您还可以使用 remote.require 从 ngx-electron 加载本机节点模块。

    fs;
    
    constructor(private _electronService: ElectronService) { 
        this.fs = this._electronService.remote.require('fs');
    }
    

    【讨论】:

      【解决方案3】:

      您的浏览器无法访问服务器上的文件系统。 fs 不应该在浏览器中加载

      【讨论】:

      • 还有其他方法可以访问电子中的文件系统吗?它是为桌面应用程序制作的,而不是为服务器使用而制作的。由于这篇文章,可以访问文件系统,但它不是用角度或打字稿制作的,所以我无法重现它:ourcodeworld.com/articles/read/106/…
      • 根据 Angular 版本,您可以访问 webpack 配置。如果你能改变它。将目标设置为节点。可能会奏效。 目标:'节点',
      • 我现在在我的项目上运行 ngject 来获取 webpack 配置,但这破坏了一些构建文件。得到错误:未捕获的ReferenceError:未定义导出......对于polyfills.bundle.js,对于styles.bundle.js,对于vendor.bundle.js和main.bundle.js......我在网上寻找帮助,但也许你们知道更好的吗?
      猜你喜欢
      • 2017-01-17
      • 1970-01-01
      • 1970-01-01
      • 2018-11-20
      • 2020-11-11
      • 2020-04-12
      • 1970-01-01
      • 1970-01-01
      • 2020-03-27
      相关资源
      最近更新 更多