问题
I need get screen resolution with node.js, but the following code don't work.
var w = screen.width;
var h = screen.height;
This also don't work.
var w = window.screen.width;
var h = window.screen.height;
Someone know how to get screen resolution with node.js ? Thank you.
回答1:
There is now a screenres module via npm:
https://www.npmjs.com/package/screenres
回答2:
You should retrieve the window.screen.width
and window.screen.height
in your client-side JavaScript code and send that information to your server-side Node.js application via AJAX, WebSocket, as form data, etc.
For example:
(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);
This is common and is not related to the server-side technology. Doesn't matter what you use at the back-end (Node.js, Python, Ruby, PHP, Java, ASP.NET, etc.), you should send a data from client to server since the server doesn't deal with the user's browser directly.
回答3:
I solved the problem with phantomJS
.
Install phantomJS
:
sudo apt-get install phantomjs
Create app.js file:
var w = screen.width;
var h = screen.height;
console.log(w+"x"+h);
phantom.exit();
Execute:
phantomjs app.js
Return:
1366x768
回答4:
This is quite an overkill, but the node module I found doesn't work anymore and it doesn't handle multiple displays anyway:
npm install nightmare
And then if you want for exampnle the size and coordinates of the external monitor if available:
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;
};
来源:https://stackoverflow.com/questions/18989295/how-to-get-screen-resolution-with-node-js