如何使用Node.js获取屏幕分辨率

5
我需要使用node.js获取屏幕分辨率,但以下代码不起作用。
var w = screen.width;
var h = screen.height;

这个也不起作用。
var w = window.screen.width;
var h = window.screen.height;

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


如果服务器没有运行图形界面,这很可能是情况吗? - Joe Doyle
1
为什么要成为服务器? - Jean-Philippe Leclerc
4
因为Node.js不在客户端运行,而是在服务器上运行。 - hexacyanide
Joe,在这种情况下,我确定用户有图形用户界面。 - Agneli
3
"Nodejs不在客户端运行"这种说法是荒谬且不正确的。这就像说"Java不在客户端运行"一样。ElectronJs和其他许多技术都可以在工作站上运行nodejs。 - Arbiter
5个回答

5

0

这有点过度了,但我找到的节点模块不再起作用,而且它也无法处理多个显示器:

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;
};

0

我用 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

0
你应该在客户端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等),你都应该将数据从客户端发送到服务器,因为服务器不能直接处理用户的浏览器。

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

0

使用screenz

const { width, height } = require("screenz");

console.log(width);
//=> 1920

console.log(height);
//=> 1080

1
整个模块只是const robot = require("robotjs") module.exports = robot.getScreenSize()而且robotjs不支持多监视器。 - Arbiter
@Arbiter,您希望如何处理多显示器支持? - Richie Bendall
我希望它告诉我显示器的数量以及每个显示器的宽度和高度? - Arbiter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接