I know that Angular 2 is run on a web browser, which does not have access to the file system.
However, I'm using Electron as my front-end, and also running the app via electron:
"build-electron": "ng build --base-href . && cp src/electron/* dist",
"electron": "npm run build-electron && electron dist"
Therefore, I run it with npm run electron
which at the very end runs electron dist
.
Since I'm running through electron
and not ng
I would think that I should be able to access the filesystem. However, when I do:
import * as fs from 'fs'
I get an error:
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 resulting in the error:
this.config = ini.parse(fs.readFileSync('../../CONFIG.ini', 'utf-8'))
Does anyone have any idea what's causing this?
Thanks.
Solved it by:
1) Eject webpack:
ng eject
2) Add
target: 'electron-renderer'
to themodule.exports
array insidewebpack.config.js
3) Require remote, since we're in the
renderer
, butfs
is only available in themain process
(Read more):var remote = require('electron').remote;
4) Require fs (this time using remotes implementation of require):
var fs = remote.require('fs');
And now it works!
I'm late to the party but I also stumbled upon this problem recently. To the late comers, you can use ngx-fs
https://github.com/Inoverse/ngx-fs
Usage:
I had the same problem and could solve it in an easier way:
Just download this project as start, the 'require'-s are already in the webpack.config.js file (along with the integration of angular, electron and so on): https://github.com/maximegris/angular-electron
import 'fs' into home.ts (or into any other component) as mentioned by @Matthias Sommer above:
import * as fs from 'fs'
As I understand it, you build the application with Webpack.
You can expose all Node modules via the externals array in your webpack config.
Since they are provided through the Webpack externals, one does not have to require them but use them with imports.
You can read more about this problem in my article.