【问题标题】:How to get screen resolution with node.js如何使用 node.js 获得屏幕分辨率
【发布时间】:2013-09-30 02:56:52
【问题描述】:

我需要使用 node.js 获取屏幕分辨率,但以下代码不起作用。

var w = screen.width;
var h = screen.height;

这也行不通。

var w = window.screen.width;
var h = window.screen.height;

有人知道如何使用 node.js 获得屏幕分辨率吗? 谢谢。

【问题讨论】:

  • 如果服务器没有运行图形界面怎么办?很可能是这种情况?
  • 为什么会是服务器?
  • 因为 Node.js 不运行客户端,它运行在服务器上。
  • 乔,在这种情况下,我确定用户有一个 GUI
  • “Nodejs 不在客户端运行” - 愚蠢且不真实。这就像说“Java 不在客户端运行”。 ElectronJs 和许多其他技术都在工作站上运行 nodejs。

标签: javascript node.js client-server screen-resolution


【解决方案1】:

您应该在客户端 JavaScript 代码中检索 window.screen.widthwindow.screen.height,并通过 AJAX、WebSocket、表单数据等将这些信息发送到服务器端 Node.js 应用程序。

例如:

(function(w) {
    $.ajax({
        type: 'POST',
        url: '/echo/json',
        data: {
            w: w.screen.width,
            h: w.screen.height
        },
        success: function() {
            console.log(arguments);
        },
        dataType: 'json'
    });
})(window);

这很常见,与服务器端技术无关。无论您在后端使用什么(Node.js、Python、Ruby、PHP、Java、ASP.NET 等),您都应该将数据从客户端发送到服务器,因为服务器不处理直接访问用户的浏览器。

【讨论】:

  • 谢谢尤金,但我想获得相同的服务器屏幕分辨率。
  • 如果您在服务器上运行浏览器,您可以在该浏览器中运行客户端脚本,并以同样的方式将数据发送到服务器端应用程序。
  • 在 Linux 服务器运行多个显示器的常见情况下,X11 在内部默认为单个巨大的聚合窗口。 Phantomjs 将返回该分辨率。 Eugene 的答案将返回运行浏览器的任何显示器的分辨率,无论操作系统如何,或者其窗口管理器是如何配置的。
【解决方案2】:

我用phantomJS解决了这个问题。

安装phantomJS:

sudo apt-get install phantomjs

创建 app.js 文件:

var w = screen.width;
var h = screen.height;

console.log(w+"x"+h);

phantom.exit();

执行:

phantomjs app.js

返回:

1366x768

【讨论】:

    【解决方案3】:

    现在有一个通过 npm 的 screenres 模块:

    https://www.npmjs.com/package/screenres

    【讨论】:

      【解决方案4】:

      这有点矫枉过正,但我​​发现的节点模块不再工作了,它也不能处理多个显示:

      npm install nightmare
      

      然后,如果您想了解外部显示器的大小和坐标(如果有):

      const getBounds = async () => {
        const nm = new Nightmare({
          webPreferences: {
            nodeIntegration: true,
          },
        });
        const bounds = nm
          .goto('about:blank')
          .evaluate(() => {
            const electron = require('electron');
            const displays = electron.screen.getAllDisplays()
            const display = displays.find((d) => d.bounds.x !== 0 || d.bounds.y !== 0) || displays[0];
            return display.bounds;
          }).end();
        return bounds;
      };
      

      【讨论】:

        【解决方案5】:

        使用screenz

        const { width, height } = require("screenz");
        
        console.log(width);
        //=> 1920
        
        console.log(height);
        //=> 1080
        

        【讨论】:

        • 这整个模块只是``` const robot = require("robotjs") module.exports = robot.getScreenSize() ``` 而且robotjs不支持多显示器顺便说一句。
        • @Arbiter 您希望它如何处理多显示器支持?
        • 我想让它告诉我显示器的数量和每台显示器的宽度和高度?
        猜你喜欢
        • 2014-10-25
        • 1970-01-01
        • 2011-11-10
        • 2011-04-10
        • 2013-06-14
        • 1970-01-01
        • 1970-01-01
        • 2012-01-31
        • 1970-01-01
        相关资源
        最近更新 更多