用电子打开文件

时间:2016-12-11 10:01:11

标签: javascript node.js electron

我正在使用一个简单的电子文本编辑器,它应该进行基本的CRUD操作。

我能够使用FS节点模块读取和写入文件,我可以通过电子对话框轻松获取文件的路径。我希望我的用户能够使用该程序打开.txt文件,但不要求他或她先启动程序,然后选择该文件。

想象一下,您的桌面上有一个文本文件,您可以使用myAmazingTextEditor设置所有.txts,因此当您双击它时,它会打开应用程序并在文本区域中显示该文件的内容。

基本上,我的问题是处理传入的文件。如何检查文件是否正在打开应用程序?

非常感谢大家!

1 个答案:

答案 0 :(得分:0)

我在用 Electron 构建应用程序时遇到了同样的问题。我设法在 this 站点上找到了解决方案:

主要内容:

// read the file and send data to the render process
ipcMain.on('get-file-data', function(event) {
  var data = null
  if (process.platform == 'win32' && process.argv.length >= 2) {
    var openFilePath = process.argv[1]
    data = openFilePath
  }
  event.returnValue = data
})

在渲染器中:

var data = ipcRenderer.sendSync('get-file-data')
if (data ===  null) {
    console.log("There is no file")
} else {
    // Do something with the file.
    console.log(data)
}