使用Electron访问Angular 2应用程序中的文件系统
我知道Angular 2运行在无法访问文件系统的Web浏览器上。
不过,我使用Electron作为我的前端,并通过电子运行应用程序:
"build-electron": "ng build --base-href . && cp src/electron/* dist", "electron": "npm run build-electron && electron dist"
所以我用npm run electron
运行它,最后运行electron dist
。
由于我通过electron
运行,而不是ng
我会认为我应该能够访问文件系统。 但是,当我这样做的时候:
import * as fs from 'fs'
我收到一个错误:
ng:///AppModule/AppComponent_Host.ngfactory.js:5 ERROR TypeError: __WEBPACK_IMPORTED_MODULE_0_fs__.readFileSync is not a function(…)
同样,当我尝试: var fs = require('fs');
我得到:
ng:///AppModule/AppComponent_Host.ngfactory.js:5 ERROR TypeError: fs.readFileSync is not a function
这是导致错误的呼叫:
this.config = ini.parse(fs.readFileSync('../../CONFIG.ini', 'utf-8'))
有谁知道是什么原因造成的?
谢谢。
据我所知,你用Webpack构build应用程序。
您可以通过webpackconfiguration中的外部数组公开所有的Node模块。
module.exports = { "externals": { "electron": "require('electron')", "child_process": "require('child_process')", "fs": "require('fs')", "path": "require('path')", ... } }
由于它们是通过Webpack外部提供的,所以不需要它们,而是将它们与import一起使用。
import * as fs from 'fs'
您可以在我的文章中阅读有关此问题的更多信息。
解决它:
1)popupwebpack: ng eject
2)将target: 'electron-renderer'
到module.exports
数组中
3)需要远程,因为我们在renderer
,但fs
只在main process
可用( 阅读更多 ): var remote = require('electron').remote;
4)需要fs(这次使用remotes实现require): var fs = remote.require('fs');
现在它工作!