- How to Run or Call Executable (EXE) From JavaScript?
- Why Do Developers Need to Call an EXE File From JavaScript?
- Methods of Calling an EXE File From JavaScript
- 1. Microsoft ActiveX Objects
- 2. Using a Chrome Extensions API
- 3. Using the WebSocket Protocol
- 4. Using a Node.js Module
- 5. Using the ShellExecute Function
- Conclusion
- Handling files in JavaScript
- File Handling in JavaScript
- fs.open()
- fs.appendFile()
- fs.writeFile()
- fs.readFile()
- fs.unlink()
- fs.rename()
- Miscellaneous
- Conclusion
How to Run or Call Executable (EXE) From JavaScript?
Don’t worry; you are not alone. JavaScript is a highly diverse programming language primarily used for web development. Developers can create highly interactive and intuitive web pages that dynamically update based on user input. But sometimes developers need to interact with numerous other softwares outside the browser.
In such cases, experts call an executable file or “exe” from within their JavaScript code. As a result, this function can be useful for various tasks, such as launching an external application, running a script or command-line tool, or performing system-level tasks. In addition, this function can prove instrumental in file management, data processing, or automation domains.
If you cannot call exe from within your JavaScript code, don’t stress. In this guide, we go over five methods that you can employ to run or call the exe file from JavaScript.
Before we start, let’s look at why we need to call an exe file from JavaScript.
Table of Contents
Why Do Developers Need to Call an EXE File From JavaScript?
Calling an exe file from JavaScript can help diversify your application’s capabilities and scope while providing users with a more robust and comprehensive experience. Calling an exe file can be a flexible and powerful solution whether you need to access system resources, perform complex calculations, or integrate with other software applications.
Apart from these benefits, there are numerous perks for calling an exe file from JavaScript:
- Customization and Flexibility: Calling an exe file from JavaScript can enhance the functionality and customizability of your web application in several ways. This proves to be instrumental in creating more sophisticated and powerful applications custom-tailored to users’ specific needs
- Security and Stability: When you use an external application to perform certain tasks, you can drastically enhance the stability and security of your web application. For instance, if you need to access system resources or exploit sensitive data. Then using an external application designed specifically for this task helps to reduce security risks and contributes to the reliability and stability of your application
Methods of Calling an EXE File From JavaScript
Depending on the unique use cases and requirements, multiple methods can be used to call an executable file from JavaScript. However, the goal is to ensure seamless integration between the web page and external application, enabling users to access features unavailable through the web page alone.
Let’s look at five techniques for calling an exe file from JavaScript:
1. Microsoft ActiveX Objects
ActiveX is a software component that can access system resources and perform various tasks within a web page. ActiveX controls can call an exe file by creating an instance of the Shell.Application object and using its ShellExecute method. Here’s an example of code you can use:
var shell = new ActiveXObject("Shell.Application"); shell.ShellExecute("path/to/exe", "", "", "open", "1");
This ShellExecute method employs four parameters:
- The path of the .exe file that you want to launch is the first parameter
- The command-line arguments that you want to pass to your .exe file is your second parameter
- The working directory for the .exe file is the third parameter
- The fourth parameter is the verb that you use to open the file, e.g. (“print” to print the file or “open” to launch the file
- Any additional flags that you want to use can be considered the fifth parameter
Although you can use ActiveX objects to call an exe file from JavaScript, it is crucial to know that the service only works on Internet Explorer, so this method is not viable if you use any other browser.
2. Using a Chrome Extensions API
This method is particularly useful if you are developing a browser extension. You can use the Chrome Extensions API to launch a .exe file from JavaScript.
For instance, the Chrome Extension API allows you to send a message to a native application to launch the .exe file through the chrome.runtime.sendNativeMessage . Here is an example of code you can use:
chrome.runtime.sendNativeMessage('com.example.native', < 'path': 'path/to/exe', 'args': ['arg1', 'arg2', 'arg3'] >, function(response) < console.log('Native response:', response); >);
The code above sends a message to the native application with the com.example.native ID. The native application then uses the operating system’s API to launch the .exe file.
3. Using the WebSocket Protocol
Employing a WebSocket Protocol enables real-time client and server communication. This bidirectional communication makes it an optimum choice for applications that require real-time updates. Here is an example code that you can use to call an exe file using a WebSocket Protocol:
var socket = new WebSocket("ws://localhost:2134"); socket.onopen = function(event) < socket.send("run:C:\\path\\to\\executable.exe"); >;
In the code above, we create a new instance of the “WebSocket” object and then proceed to connect to a WebSocket server running on a localhost port 2134. Whenever the connection is established, we can send a message to the server requesting it to run the .exe file. On the server side, you must execute the appropriate command based on the message received.
4. Using a Node.js Module
If you are a developer working on a Node.js application, you can use the Child Process module to generate a new process and execute the required command. This module uses several methods for executing, such as exec , spawn , and fork . We will use the exec method to call an exe file from Node.js below:
const < exec >= require('child_process'); // Define the path to the executable file const executablePath = 'path/to/executable.exe'; // Call the executable file and log its output exec(executablePath, (error, stdout, stderr) => < if (error) < console.error(`Error: $`); return; > console.log(`stdout: $`); console.error(`stderr: $`); >);
In the code above we have used the exec method from the child_process module to execute an external command denoted by executablePath variable, which points to the path of the executable file that the user wants to execute.
This method takes a callback function and only executes it when the command is complete or finished. Then the callback function receives three arguments: error , stdout , and stderr .
An error argument is an error object applicable only when the command encounters an error. In normal circumstances, it is null.
The stdout argument has the standard command output, and the stderr argument contains the standard error output of the command. In the code above, if an error object is returned, console.error() logs it to the console. Otherwise, console.log() and console.error() is used for logging standard output and standard error output to the console, respectively.
5. Using the ShellExecute Function
Users can also call an exe file from JavaScript using the ShellExecute function in Windows. You can call this function using either the Windows Script Host (WSH) or the Windows Script Components (WSC) technology. Here’s how to use the ShellExecute function:
var shell = new ActiveXObject("Shell.Application"); shell.ShellExecute("C:\\path\\to\\executable.exe", "", "", "open", 1);
In the code above, we generate a new instance of the Shell.Application object and then use the ShellExecute technique to launch the executable. The path to the executable file is the first parameter of the ShellExecute method, the second parameter is any command-line arguments that need to be passed to the executable, the third parameter is the working directory for the executable, the fourth parameter is the operation to act, e.g. (open, explore, etc.), and the fifth parameter is an integer that determines how the window is displayed for instance, (1 for normal, 0 for hidden).
Conclusion
This guide explains the importance and various use cases of running or calling an exe file from JavaScript and five ways you can run or call the exe file. We hope that this tutorial was helpful in your journey of creating stunning web applications.
Lastly, let us know in the comments below:
- Were you successfully calling the exe file from JavaScript using the above-mentioned techniques?
- Have you ever called an executable file from JavaScript in your projects? If so, which method did you use, and what are some limitations?
- Are there any other useful techniques for calling the exe file from JavaScript that we missed?
Feel free to share this guide with your fellow developers, and as usual, Happy Coding!
Handling files in JavaScript
Invicti Web Application Security Scanner – the only solution that delivers automatic verification of vulnerabilities with Proof-Based Scanning™.
JavaScript is a popular programming language that lets you handle files in the browser. Let’s learn how!
The environment NodeJS is used for different scripts which include file handling. NodeJS is nothing but an environment to run JavaScript code. I hope you have a basic understanding of NodeJS.
Let’s jump into the tutorial to learn about file handling in JavaScript.
File Handling in JavaScript
Handling files includes different operations like creating, reading, updating, renaming, and deleting. We have to access the files from the system which is not possible for us to write it from scratch. So, NodeJS provides a module called fs (file system) for file handling.
Let’s see different methods from the fs module.
fs.open()
The method fs.open() will take two arguments path and mode.
The path is used to locate the file.
The argument mode is used to open the file in different modes like appending, writing, and reading.
If you open any file in a specific mode, then you can perform only one type of operation corresponding to the mode you have passed to the method. Let’s see the list of modes and corresponding operations.
Mode | Operation |
‘r’ | Opens a file in reading mode |
‘a’ | Opens a file in appending mode |
‘w’ | Opens a file in writing mode |
‘a+’ | Opens a file in appending and reading mode |
‘w+’ | Opens a file in writing and reading mode |
‘r+’ | Opens a file in reading and writing mode |
If the file doesn’t exist on the given path, then it will create a new empty file. Let’s see the code for opening a file in different modes.
const fs = require("fs"); fs.open("sample.txt", "w", (err, file) => < if (err) throw err; console.log(file); >);
The method fs.open() will throw an error if the file doesn’t exist while opening in reading mode. It will create a new empty file in writing and appending modes.
We can perform different operations on the opened file. We will write a complete program at the end of this tutorial after learning some more essential methods from the fs module.
fs.appendFile()
The method fs.appendFile() is used to append the content at the end of the file. If the file doesn’t exist in the given path, then it will create a new one. Append some content to the file using the below code.
const fs = require("fs"); fs.appendFile("sample.txt", "Appending content", (err) => < if (err) throw err; console.log("Completed!"); >);
fs.writeFile()
The method fs.writeFile() is used to write the content to the file. If the file doesn’t exist in the given path, then it will create a new one. Try the below code for writing the content to a file.
const fs = require("fs"); fs.writeFile("sample.txt", "Writing content", (err) => < if (err) throw err; console.log("Completed!"); >);
fs.readFile()
The method fs.readFile() is used to read the content from a file. It will throw an error if the file doesn’t exist in the given path. Examine the following code for the method.
const fs = require("fs"); fs.readFile("sample.txt", (err, data) => < if (err) throw err; console.log(data.toString()); >);
fs.unlink()
The method fs.unlink() is used to delete the file. It will throw an error if the file doesn’t exist in the given path. Have a look at the code.
const fs = require("fs"); fs.unlink("sample.txt", (err) => < if (err) throw err; console.log("File deleted!"); >);
fs.rename()
The method fs.rename() is used to rename the file. It will throw an error if the file doesn’t exist in the given path. Rename the next file with the following code. Be smart!
const fs = require("fs"); fs.rename("sample.txt", "sample_one.txt", (err) => < if (err) throw err; console.log("File renamed!"); >);
Miscellaneous
Now, you are familiar with different file handling methods from the fs (file system) module. You can perform most of the file operations using the methods that you have seen in this tutorial. As we promised, let’s see an example script that opens a file and read content from it using the fs.open() and fs.readFile() methods respectively.
const fs = require("fs"); fs.open("sample.txt", "r", (err, file) => < if (err) throw err; fs.readFile(file, (err, data) =>< if (err) throw err; console.log(data.toString()); >); >);
Conclusion
That’s it for this tutorial. You can use the file handling methods to automate some of the boring stuff in your day-to-day tasks. I hope you have learned the essential methods for handling files.