windows-interact
This library is a collection of tools for interacting with and automating Windows. It is designed to simplify and enhance existing tools while providing access to powerful new features.
With windows-interact
, NodeJS gains the following functionality:
- Control over audio devices
- Shutdown, Restart, Lock, Sleep, or start Screen Saver
- Send Toast notifications or Tray Balloons
- Mixin replacements for the browser's alert(), confirm(), and prompt()
- Native Windows File Picker
- Take screenshots
- Asynchronous Text to speech
- Play audio files in the background
- Manipulate windows (Maximize, Minimize, etc.)
- Manage a list of registered apps (with lots of extra features)
- Manage processes
- Enhanced logging and error throwing
- VERY Advanced PowerShell session manager
- More advanced than node-powershell, with automatic output collection and seperation, and the ability to run multiple command in succession by passing in array.
The current released version is 1.3.1. See the release notes if this version number differs from below
Patch 1.3.1:
- Fixed Win.PowerShell.newCommand rejecting empty 2nd and 3rd parameters
New in version (1.3.0):
- New display methods, including:
- Get/Set resolution
- Set projection mode
- Added
Win.get.user.idleTime()
to check the idle time of the user (last keyboard or mouse input) - Added detection for audio transmitted through both input and output (
Win.get.audioDevices.output.transmitting
,Win.get.audioDevices.input.transmitting
).
What's changed:
- Added
stackTrace
as a verbosity option. From now on, most internal methods that use PowerShell will start hiding their large and irrelevant error stack trace unless this option is enabled Win.log()
now parses Javascript objects properly (Similar to console.log. Formatting and color is coming soon)- App Manager:
- Added verbosity options
- onLaunch and onKill now return the name of the relevant application
- Fixed bugs with
Win.alert()
andWin.confirm()
and now uses the same PowerShell Session under the hood to prevent excessive process spawning - Fixed a bug where Window Titles in
Win.appManager.registeredApps
would all be the same as the first app - Fixed an error associated with the AudioDeviceCmdlets module that appeared when installing windows-interact
- Fixed
Win.notify()
andWin.filePicker()
(These were broken in the last release, so sorry!) - Cleanup up miscellaneous internal code
Known issues:
Win.PowerShell()
:- Using
Start-Sleep
with any value greater than 800ms will cause some very odd issues with the internals ofWin.PowerShell()
. This is because 800ms is the extra time that each command is manually seperated to better discern output. This will be fixed in the future, but for now, avoid usingStart-Sleep
if possible
- Using
What's next:
Win.PowerShell()
is going to be optimized as much as possible and ran through with a fine tooth comb over the next few months.- There will be a lot of refactoring coming soon, this project is getting massive and its time to split it up a little.
- Better documentation / An official, actually navigateable website.
- Most or all methods will be converted to Promises instead of callbacks
- Planning on removing dependency on requestify, perhaps building my own wrapper for nodes' native request methods with zero dependencies
Got ideas? Something you want windows-interact to include? Fantastic, contact me on twitter @Arlodottxt with your suggestions or open a new Issue on Github
Installation
Install the npm package by running npm install windows-interact
in your project folder
Then, in your js file, require
the package.
const Win = ;
Windows-Interact also relies moderately on nircmd. This is included in the package but untested on another machine, so if you start having troubles, try installing it to your machine.
Documentation
Win.set
Used to set various things within Windows, as well as set preferences for windows-interact
Set Global user preferences for Windows Interact
Winset;
Display
Set the resolution of the primary display
Win.set.display.resolution(width, height, callback) => : void
Winsetdisplay;
Set the projection mode
// Accepted values are "primary", "secondary", "extend" or "duplicate"Winsetdisplay;
Audio Devices
Input
Set the volume of the current input device
WinsetaudioDevicesinput;
Set the mute state of the current input device
WinsetaudioDevicesinput;
Set the default input device in Windows
WinsetaudioDevicesinput;
Output
Set the volume of the current output device
WinsetaudioDevicesoutput;
Set the mute state of the current output device
WinsetaudioDevicesoutput;
Set the default output device in Windows
WinsetaudioDevicesoutput;
Win.get
Used to get the status of various things within Windows
User
Get the Idle time of the current user
Win.get.user.idleTime(callback) => : Promise
// Log the Idle timeWinget ; // : [hours, minutes, seconds]
Display
Get the current display resolution
Win.get.display.resolution(callback) => : void
Wingetdisplay;
Audio Devices
Input
Get the volume of the current input device
WingetaudioDevicesinput;
Get the mute state of the current input device
WingetaudioDevicesinput;
Get the default input device in Windows
WingetaudioDevicesinput;
Get the audio transmission state of the default input device (Microphone detection)
Win.get.audioDevices.input.transmitting(callback => : boolean);
WingetaudioDevicesinput;
Output
Get the volume of the current output device
WingetaudioDevicesoutput;
Get the mute state of the current output device
WingetaudioDevicesoutput;
Get the default output device in Windows
WingetaudioDevicesoutput;
Get the audio transmission state of the default output device
Win.get.audioDevices.output.transmitting(callback => : boolean);
WingetaudioDevicesoutput;
Win.log()
Win.log(message, {background: 'color', color: 'color'}); => : void
An alternative to console.log
. It pushes the output of the log to the console and can record each entry in a .txt file, while providing simple colour options for the text
Available colours for background and text are:
- Red
- Green
- Yellow
- Blue
- Magenta
- Cyan
- Black
You can set the default log file location with Win.set.preferences
, like so:
Winset;
Usage:
// Log information to the console and .txt fileWin; // Log information to the console and .txt file, with colored background and text, and don't show the timestamp (even if enabled in preferences)Win; Winlog;// Log information to the console and .txt file, and also Win.speak() itWinlog; // Log information to the console and .txt file, Win.speak() it with a specific voice, at half speed, with a black background and a blue text colourWinlog
Win.error()
An alternative to throw new Error()
or console.error
. It will push the output of the log to the console (in a red colour) with a stack trace, and record each entry in the specified log file
You can set some default options with Win.set.preferences
, like so:
Winset;
Usage:
// Log an error to the console and default .txt file (if set)Win; // Log an error to the console, but don't speak the set spokenErrorMessageWin;
Win.notify()
Show a toast notification in Windows 10 (Or tray balloon on older versions of windows)
If you need something more advanced than basic notifications, I'd recommend using node-notifier
// Show toast notification with an image or animated GIFWin; // Show single line toast notificationWin;
Win.path``
Return a properly formatted Windows path for use in Javascript. This allows you to simply copy and paste a path from the File Explorer without having to worry about character-escaping (\
) slashes.
If you are passing in a directory, surround the path with double quotes or escape the last backslash. Surrounding double quotes are always removed.
Winpath`C:\WINDOWS\system32\notepad.exe`;
Win.speak()
Speak text asynchronously. Similar to my async-sayjs package (Yep, that started here), but with some benefits and enhancments.
You can set the default text to speech voice with Win.set.preferences
, like so:
Winset;
Usage:
// Speak something asynchronously (wait for each request to finish before moving on)Win; // Speak something synchronously (Say it right now, even if something is already being said)Winspeak; // Supply a string as the second parameter to change the TTS voiceWin; // Speak something, but slowlyWin; // Speak something, then fire a callbackWin; // Speak something and Win.log() it (Same as Win.log.speak(''))Winspeak; // Stop anything currently being spoken (Queued text will continue after that)Winspeak;
Win.appManager
The App Manager is possibly the biggest part of Windows Interact. It allows you to:
- Register applications and manage them in one simple place
- Run code when a registered app is launched or killed
- Quickly launch or kill an app
- Get the title of an app window
- Check if an app is currently running
- Hide an app
- Switch to an app
To get started, you need to register your apps. You will need the absolute path of the executable at the minimum. To easily format a Windows path for use in Javascript, it is recommended that you use Win.path`C:\absolute\path`
Register a new application
WinappManager;
Group together registered apps
WinappManagerregister;
Retrieve registered applications
WinappManagerregisteredApplications
Launch a registered application
WinappManager;
Kill a registered application
WinappManager;
Launch a registered group of apps
WinappManagerlaunch;
Kill a registered group of apps
WinappManagerkill;
Hide a registered application
WinappManager;
Switch to a registered application
WinappManager;
Win.process
Win.process
is very similar to appManager
, but can be used for unregistered apps. Use sparcely and avoid loops, this is not as efficient as appManager
.
Get PID of a running process
Returns an array of PIDs associated with a running process. If no process is found, false is returned. The data is piped into a callback.
Winprocess;
Kill a running app
Kill an app by either process name or PID
Winprocess;
Run a callback when a process is killed
App must already be running, if not, it will wait until it has started and then tell powershell to wait until the app is done before continuing.
Winprocess;
Get Window Title of running application
Winprocess;
Hide an application by process name
Winprocess;
Check if a process is running
Winprocess;
Win.window()
Control a Window's state
Minimize a window
If no processName is specified, it will minimize the current window in the foreground.
// Minimize a window by process name. The ".exe" is optional.Winwindow; // Minimize the current windowWinwindow;
Maximize a window
If no processName is specified, it will maximize the current window in the foreground.
// Maximize a window by process name. The ".exe" is optionalWinwindow; // Maximize the current windowWinwindow;
Restore a window to a windowed state
If no processName is specified, it will restore the current window in the foreground.
// Restore a window by process name. The ".exe" is optionalWinwindow; // Restore the current windowWinwindow;
Resize a window
If no processName is specified, it will resize the current window in the foreground.
Winwindow; // Resize a window by process name. The ".exe" is optionalWinwindow; // Resize the current windowWinwindow;
Move a window
- X and Y are relative to the current window position.
- If no processName is specified, it will move the current window in the foreground.
Winwindow; // Move a window by process name. The ".exe" is optionalWinwindow; // Move the current windowWinwindow;
Win.cmd()
Run a command in Command Prompt.
Win; // Run a command, then do something with the outputWin; // Run a command, then do something with the output and any possible errorsWin; // Run a command, but supress any errors that occur (Don't print them to console or log)Win; // Run a command, but don't print to log Win;
Win.PowerShell()
Run one or more PowerShell commands.
You can run a single powershell command by passing a string, or run multiple commands in the same powershell instance by passing commands in an array.
When you pass an array to run multiple commands, the returned output and errors will be an array, not a string. The indexes of commands will matche the indexes of output returned
This is playing with real power. See here and here for resources on what you can do with PowerShell to automate and interact with Windows, beyond what Windows interact provides
Win; Win; // Run a command, then do something with the outputWin; // Run a command, then do something with the output and any possible errorsWin; // Run a command, but suppress any errors that occurr (Don't print them to console or log)Win; // Run a command, but do not log the output and supress any errors that occurr (Don't print them to console or log)Win; // Run multiple commands in the same powershell windowWin;
Keeping a PowerShell session open for later use
To keep a PowerShell session open, pass keepAlive: true
and ID: 'someid'
into the options
object.
Win.PowerShell.newCommand(id, command)
Issue a new command to an open PowerShell session by the assigned ID
// Keep a windows open firstWin; // Then add a new command
Win.PowerShell.endSession(id, callback)
End an open PowerShell session by ID
Win.requestTo()
Make an HTTP request the easy way.
To simplify this feature and make using it more natural, there is some flexibility with the parameters
- There are 4 default parameters which will work in every scenario (no shorthand):
url, method, formData, callback
- If the all parameters are ommited, an assumed GET request will be made.
- If the second paramter is a function, it will assume that this is a callback and an assumed GET request will be made
- If the third parameter is an object, it will send this as form data.
- If the third parameter is a function, it execute it as a callback
Win; // Make a POST requestWin; // Make a POST request, then do something with the responseWin; // Make a GET requestWin; // Make an assumed GET requestWin; // Make an assumed GET request to a predefined URL, and do nothing elseWin; // Make a PUT requestWin; // Make a PUT request, then do something with the responseWin;
Win.confirm()
An alternative to the browsers's confirm()
. Unlike the browser, it will not stop execution of code and wait for the user. It will instead show multiple dialog boxes. To chain consecutive dialog boxes, you need to wrap them in an async function (see below).
Win; Win; // Chain consecutive alerts { ifawait Win await Win; }; // Super simple self-executing async functionasync { ifawait Win await Win; else await Win; };
Win.alert()
An alternative to the browsers's alert()
. Unlike the browser, it will not stop execution of code and wait for the user. It will instead show multiple dialog boxes. To chain consecutive alerts, you need to wrap them in an async function (see below).
// Show an alert box with title and messageWin; Win; // Chain consecutive alerts { await Win; await Win;}; // Super simple self-executing async functionasync await Win; await Win;;
Win.prompt()
An alternative to the browsers's prompt()
. Unlike the browser, it will not stop execution of code and wait for the user. It will instead show multiple dialog boxes. To chain consecutive prompts, you need to wrap them in an async function (see below).
Winprompt'Message' 'Title' 'Placeholder'; Winprompt'Message'; // Chain consecutive alerts { ifawait Winprompt'Please type bananas' == 'bananas' await Win; }; // Super simple self-executing async functionasync ifawait Winprompt'Do you like Pie?' == 'Yes' await Win; else Win; ;
Win.filePicker()
Shows the native Windows File Picker (No really!) and returns the path for the selected file. If no file is selected, undefined
is returned instead.
Win; // Default everything. // windowTitle will be "Select a file".// initialDirectory will be C:\// Filter will be set to "All files"// multiSelect is disabledWin; // Have the user choose an application from Program FilesWin; // Have the user choose a very specific fileWin; // Use some defaults and have the user pick a few .png files Win; // Have the user select an image fileWin;
Win.playAudio(path);
Play an audio file in the background. Must be a .wav
format. If you try any other format, it will fall back to Windows Media Player to play it (so make sure it's installed through Optional Features).
Win;
Win.stopAudio(path);
--
Stop a playing audio file using the same path supplied to Win.playAudio()
.
Win; ;
Win.power()
Shutdown the PC
// If no delay is provided, it will shutdown immediatelyWinpower;
Restart the PC
// If no delay is provided, it will restart immediatelyWinpower;
Lock the PC
// If no delay is provided, it will lock immediatelyWinpower;
Put the PC to sleep
// If no delay is provided, it will go to sleep immediatelyWinpower;
Start the screensaver
// If no delay is provided, it will start the screensaver immediatelyWinpower;
Show the desktop
Win;
Pause or resume media being played
Same as pressing the play/pause button on keyboard.
Win;
Take a screenshot
Win.screenshot(region, path) => : Promise
// Screenshot the entire screen and save to clipboardWin;Win; // Screenshot a region of the screen and save it to clipboardWin; // Screenshot the entire screen and save to fileWin; // Screenshot the current window only and save to fileWin;