'Javascript Selenium save screenshot in a different directory

Is there a way to store a saved screenshot in a specific directory rather than the default root folder? Thanks



Solution 1:[1]

You can specify the location to save a file within fs.writeFileSync().

For example, what you are currently doing is equivalent to:

driver.takeScreenshot().then(function(data) {
    fs.writeFileSync('./Customer_Card.png', data, 'base64')
})

If you want to save your file somewhere else you simply have to include the path.

Saving into a sub-directory

const path = require('path');

driver.takeScreenshot().then(function(data) {
    fs.writeFileSync(path.joing(__dirname, 'innerDir', 'Customer_Card.png'), data, 'base64')
})

The above code would save your file to Customer_Card.png inside of the innderDir directory (which would be at the same place as the file where this code is).

So say for example I have the following project structure:

+ MyProjectDir
+---+ savePhoto.js
+---+ innerDir

After running the above code I would have:

+ MyProjectDir
+---+ savePhoto.js
+---+ innerDir
+---+---+Customer_Card.png

__dirname is an environment variable that tells you the absolute path of the directory containing the currently executing file.

Alternatively, you can use a relative path like this to get the same effect:

driver.takeScreenshot().then(function(data) {
    fs.writeFileSync('./innerDir/Customer_Card.png', data, 'base64')
})

Saving in a parent directory

Finally, if you want to go up a directory instead of into a directory you can do so like this:

driver.takeScreenshot().then(function(data) {
    fs.writeFileSync('../Customer_Card.png', data, 'base64')
})

Again to clarify, If this was your project structure:

+ MyProjectDir
+---+ innerDir
+---+---+ savePhoto.js

Then running the above code (that is in savePhoto.js) would yield:

+ MyProjectDir
+---+ Customer_Card.png
+---+ innerDir
+---+---+ savePhoto.js

This can be extended so that you can save your file at ./innerDir/innerDir2/Customer_Card.png or ../../../Customer_Card.png or even ../../innerDir/Customer_Card.png.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Timaayy