Node has become so popular and ubiquitous that it's become something of an essential installation on the machine of any developer working and building web applications today.
Very often when working on algorithms on LeetCode or when writing code for a project, you might find yourself wanting to quickly test a function (with your own test cases, or others) to make sure it's working properly before submitting it as a solution or moving forward with your work.
While you could write your own specific test files for your application (using something like Jest for instance), or test your functions in an online code editor, there may be circumstances where you'd like to test something quickly, easily and locally on your own machine with nothing more than a terminal window and a code editor. This is where Node comes in, short and sweet!
Step one in our process is to make sure you have Node installed on your machine if you don't already. Visit the official downloads page on the Node.js website to find steps to install the latest version of Node on your current operating system.
Now, for an example let's say for instance that you're working on an algorithm that involves removing the duplicate instances of a number in an array as one of its steps, and you want to make sure that your function is working properly before moving on. We can do that easily right from our command line!
We'll be working in MacOS' Terminal for this tutorial, but the process should be similar for other command line applications.
First off, open Terminal and create a file. It can be anything, but we'll use test.js:
Now, let's open that file up in our code editor! In this case we're using Visual Studio Code, so the command to open the file will be different for other editors:
Now, in our editor window we can paste or write in the function that we'd like to test. There are two key things here to note:
- We're creating a test case by creating a const named arr that will be passed in as our argument.
- We're calling the function as a console.log, a feature that normally prints something to the console in a browser; in this case our "browser" is our command line through Node!
Now we save the file and go back to our command line. Typing the following command will tell Node to open and run our test.js file:
And we'll see the following:
And there we go!
We know that's the proper expected output (in this case an array with all duplicate numbers removed), and that it worked for the test case we gave. We could change the array to whatever we wanted, or we could console.log the function multiple times with different arguments in order to test further.
If you've come this far, thanks so much for reading! I hope this little tip helps out with your own development and adds one more tool to your toolbox.