Electron 中的错误消息和控制台日志?

2022-01-10 00:00:00 debugging node.js electron javascript

在开发过程中如何在 Electron 中查看错误消息和控制台日志?另外,是否可以将日志直接写入文件?

How do you view error messages and console logs in Electron during development? Also, is it possible for the logs to be written directly into a file?

有点像 Chrome 的开发工具显示的错误和控制台日志:除了在 Electron 而不是 Chrome 中.

Kind of like the errors and console logs displayed by Chrome's dev tools: Except in Electron rather than Chrome.

推荐答案

在您的 BrowserWindow 上调用函数 openDevTools() 这将打开您在 Chrome 中找到的相同开发工具.我在我的博客 http://www.mylifeforthecode.com/debugging-renderer-process-in-electron/.

On your BrowserWindow call the function openDevTools() this will open the same dev tools you find in Chrome. I wrote about this on my blog at http://www.mylifeforthecode.com/debugging-renderer-process-in-electron/.

这是一个包含 openDevTools 的简单 main.js 文件:

Here is a simple main.js file that includes openDevTools:

var app = require('app');
var BrowserWindow = require('browser-window');

var mainWindow = null;

app.on('window-all-closed', function() {
  if (process.platform != 'darwin')  
    app.quit();
});

app.on('ready', function() {    
  mainWindow = new BrowserWindow({width: 800, height: 600});  
  mainWindow.loadUrl('file://' + __dirname + '/index.html');
  mainWindow.openDevTools();
  mainWindow.on('closed', function() {
    mainWindow = null;
  });  
});

您也可以使用远程模块通过渲染器进程访问它.对于我一直在修补的应用程序,我将函数 toggleDevTools 绑定到 F12.像这样的:

You can also access this via a renderer process using the remote module. For the apps I have been tinkering with I bind the function toggleDevTools to F12. Something like this:

  var remote = require('remote');           
  document.addEventListener("keydown", function (e) {  
    if (e.keyCode === 123) { // F12
      var window = remote.getCurrentWindow();
      window.toggleDevTools();         
    }
  });

请注意,我只在 Windows 中使用 Electron 测试了上述内容.我假设 Linux 和 Mac 版本的工作方式相同.如果您运行的是 Mac 或 Linux,请告诉我是否没有.

Note that I have only tested the above with Electron in Windows. I am assuming the Linux and Mac versions work the same. If you are running Mac or Linux please let me know if they do not.

相关文章