Welcome folks today in this blog post we will be taking screenshot of desktop
in command line using screenshot-desktop
library. All the full source code of the application will be given below.
Get Started
In order to get started you need to install the below library using the npm
command as shown below
npm i screenshot-desktop
And now you need to make an index.js
file and copy paste the following code
index.js
1 2 3 4 5 6 7 8 |
const screenshot = require('screenshot-desktop') let fs = require('fs') screenshot().then((img) => { console.log(img) fs.writeFileSync("output.png",img) }).catch((err) => { }) |
As you can see guys in the above code we are including the screenshot-desktop
module and then we are using it to take the screenshot
of the desktop and then it returns a promise
and inside that we have the buffer
image and we can saving it using the fs
module and inside it we have the method writeFileSync()
which saves the file with the name of the file as the first argument and in the second argument we are passing the buffer data of the image.
Get List of Screens
We can even get the no of displays
and screens using the listDisplays()
method as shown below
1 2 3 4 5 6 7 |
screenshot.listDisplays().then((displays) => { // displays: [{ id, name }, { id, name }] screenshot({ screen: displays[displays.length - 1].id }) .then((img) => { // img: Buffer of screenshot of the last display }); }) |
As you can see this method returns the id
and name
of the screen as the result. And accordingly we can take the screenshot
of the screen you selected.
Custom Path and Filename
You can even provide the custom path
and the filename
for the output as shown below
1 2 3 4 5 6 7 |
screenshot({ filename: 'shot.jpg' }).then((imgPath) => { // imgPath: absolute path to screenshot // created in current working directory named shot.png }); // absolute paths work too. so do pngs screenshot({ filename: '/Users/brian/Desktop/demo.png' }) |