In this exercise, we will discuss the exec() method, its risks, and alternatives.

The exec() method takes a string as an argument and runs it as a shell command, enabling shell syntax within JavaScript. The danger is that unrestricted commands can access, modify, and delete files. For example:

user_input = "cat *.js"; exec(user_input);

exec(), combined with the user input above, allows an attacker to print out all the JavaScript files in the current directory.

The execFile() method is an alternative that works similarly to exec() but requires separation of the commands and its arguments. This prevents piped commands and path variable access. Consider the following example:

import { exec, execFile } from "child_process"; // Spawns a shell with the input as is exec("ls -lah /tmp"); // Requires a command and specified arguments to execute execFile("ls", ["-lah", "/tmp"]);

The arguments for the command ls must be separated in the execFile() method call. This separation ensures that an attacker cannot inject their malicious commands. Whereas exec will allow for additional unintended commands in the input, execFile will detect an error.



Run the terminal command node app.js to launch a web application that uses exec to execute the bash command echo to print the message inside the text box. You may need to refresh the integrated browser window to see the web page.

Try appending the following strings that fit two bash commands by using the character ;:

  • "Hello\nWorld!"; ls
  • "Hello\nWorld!"; cat example.txt
  • "Hello\nWorld!"; rm example.txt.

Click Check Work to move on to the next checkpoint.


Secure our application by using execFile(). At the top of app.js, import the execFile method from child_process instead of exec.

Click Check Work to move on to the next checkpoint.


Let’s implement the execFile() method!

On line 17, replace the exec method with execFile and delete its first argument `echo -e ${msg}`. The first argument of execFile() will be the "echo" command. The second argument will be the command flags as a string array: ["-e", msg]. The third and last argument is the callback function which can be the same as the exec method.

Click Check Work, and execute the updated version of the application by using CTRL / CMD + C in the terminal and running the node app.js command again. Feel free to retry the inputs from the first checkpoint.

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?