Run JavaScript in Sublime Text

Use Node to Check Your Code with a Shortcut

Over the past couple of months I have spent at a coding bootcamp, I’ve seen a lot of people working through interview questions on their own machines. When they feel they have a good solution, they copy their function from Sublime Text and paste it into Chrome dev tools. Debugging with this workflow is painful and tedious — there is a better way!

Sublime Text build systems allow you to set up the editor to run your code in any environment installed on your computer. This is how you set up Sublime Text to run your JavaScript in Node.js in less than five minutes:

  • If you haven’t already, install Node on your machine (instructions here).
  • In Sublime Text, go to Tools → Build System → New Build System… —
  • This will open a new document called ‘untitled.sublime-build’ with a pre-populated object:
{
“shell_cmd”: “make”
}
  • Replace this with:
{
“cmd”: [“/usr/local/bin/node”,”$file”], //
“selector”: “source.js”
}
  • “/usr/local/bin/node” is the default install location for node. If you receive an [ErrNo2] when trying to run the build system, find the path to node on your computer and replace “/usr/local/bin/node”.
  • Save the file as ‘node.sublime-build’
  • Now, all you have to do is press Command+B (or goto Tools → Build System → Node) and your code will run in Node! A console will pop up from the bottom of the editor to log any errors or console.logs you have in your code. This is the same as if you had saved your file, and ran the below in the terminal.
$ node yourfile.js 
  • Finally, pat yourself on the back, because you have made your workflow and the world a more efficient place, and given a slight break to your Ctrl, C, and V keys.