Accessing the file system in an Angular 2 application using Electron

I know that Angular 2 runs in a web browser that does not have access to the file system.

However, I use Electron as my front-end, and also run the application via electron:

"build-electron": "ng build --base-href . && cp src/electron/* dist",
"electron": "npm run build-electron && electron dist"

So I run it with the help npm run electronthat works at the very end electron dist.

Since I run electron, and not ng, I think I should have access to the file system. However, when I do this:

import * as fs from 'fs'

I get an error message:

ng:///AppModule/AppComponent_Host.ngfactory.js:5 ERROR TypeError: __WEBPACK_IMPORTED_MODULE_0_fs__.readFileSync is not a function(…)

Similarly, when I try: var fs = require('fs');

I get:

ng:///AppModule/AppComponent_Host.ngfactory.js:5 ERROR TypeError: fs.readFileSync is not a function

This is the call causing the error:

this.config = ini.parse(fs.readFileSync('../../CONFIG.ini', 'utf-8'))

Does anyone know what that means?

Thank.

+8
source share
5

:

1) -: ng eject

2) target: 'electron-renderer' module.exports webpack.config.js

3) , renderer, fs main process (): var remote = require('electron').remote;

4) Require fs ( require): var fs = remote.require('fs');

!

+7

, Webpack.

Node externals webpack.

module.exports = {
   "externals": {
      "electron": "require('electron')",
      "child_process": "require('child_process')",
      "fs": "require('fs')",
      "path": "require('path')",
      ...
   }
}

Webpack, , .

import * as fs from 'fs'

.

+2

, . ngx-fs

https://github.com/Inoverse/ngx-fs

:

const fs = this._fsService.fs as any;
fs.readdir("\\", function (err, items) {
   if (err) {
      return;
   }
   for (let i = 0; i < items.length; i++) {
     console.log(items[i]);
   }
});
+2

Angular CLI: 7.0.7
Node: 8.12.0
OS: win32 x64
Angular: 7.0.4

ng eject, , Angular 8.0

: The 'eject' command has been disabled and will be removed completely in 8.0.

, native.js src :

'window.fs = require('fs');

angular-cli.json:

"scripts": [
    "native.js"
]

polyfills.ts:

'declare global {
    interface Window {
        fs: any;
    }
}'

:

'window.fs.writeFileSync('sample.txt', 'my data');'

+2

, :

  • Just load this project as start, "require'-s" are already in the webpack.config.js file (along with integration of angular, electron, etc.): https://github.com/maximegris/angular-electron

  • import 'fs' into home.ts (or any other component) as mentioned by @Matthias Sommer:

import * as fs from 'fs'

  1. Use 'fs' :)
0
source

Source: https://habr.com/ru/post/1683732/


All Articles