Before I continue, allow me to apologise: I know you expressed a slight preference for Javascript over AppleScript. However, my Javascript is pants, whilst I already know how to accomplish it using the latter, and it definitely provides one way to obtain image data from the clipboard straight from the command-line.
The following one-liner (spread over four lines just for ease of reading) will take the image from the clipboard and save it to a file with the name set as the current date and time, located in your present working directory:
osascript -e "tell application \"System Events\" to ¬
write (the clipboard as JPEG picture) to ¬
(make new file at folder \"$(pwd)\" with properties ¬
{name:\"$(date +%Y-%m-%d\ at\ %H.%M.%S).jpg\"})"
If you choose to use this method of mine, I suggest creating an alias/function to wrap it up inside of, which you can then just call by typing the function name +/- a parameter if you wanted to specify the filename manually (with a small tweak to the final part of the above command where the filename is declared).
EDIT: I went ahead and wrote a shell script that does all this for you:
#!/bin/bash
# Filename: SaveMyScreenshot (executable)
# Author: CK 2017
# ----------------------------------------------------
# Takes a screenshot to the clipboard then saves the
# clipboard image to a file in jpeg format.
#
# Usage: SaveMyScreenshot [[path/]filename]
#
# If no filename is specified, the image will be saved
# to the present working directory and named using the
# current date and time. If more than one argument is
# given, all but the first argument are ignored.
#
# e.g.
#
# SaveMyScreenshot
#
# SaveMyScreenshot ~/Desktop
#
# SaveMyScreenshot ~/Desktop/foo.jpg
# ----------------------------------------------------
screencapture -c
folder=$(pwd)
filename=$(date +%Y-%m-%d\ at\ %H.%M.%S).jpg
if [ $# -ne 0 ]; then
if [[ -d $1 ]]; then
if [ "$1" != "." ]; then folder=$1; fi
else
a=$(dirname "$1")
b=$(basename "$1" .jpg)
if [ "$b" != "" ]; then filename=$b.jpg; fi
if [ "$a" != "." ]; then folder=$a; fi
fi
fi
osascript -e "tell application \"System Events\" to ¬
write (the clipboard as JPEG picture) to ¬
(make new file at folder \"$folder\" ¬
with properties {name:\"$filename\"})"
This can be copied and pasted into a plain text file called "SaveMyScreenshot", made executable by running the command chmod +x /path/to/SaveMyScreenshot
in Terminal, then moved to one of the directories specified in $PATH
(I use /usr/local/bin).
From then on, you can simply type SaveMyScreenshot
as you would any other command in Terminal.
P.S. Don't forget to comment out or delete the line in the script that takes the screenshot (screencapture -c
). I believe you have your own, preferred method of obtaining your screenshot, and I only put this in for my own testing purposes and for completeness in case anyone else might find this answer useful in a more general context.