Starting A Node.js Project

I’d been playing with various code bins and online IDEs for a while, but I was having trouble finding best practices.

How do I set up a JavaScript project locally?

What’s the best way to organize my Node.js code?

Programming has a lot of personal preferences that come along with it (for example, a laptop is not a phone, so trackpad scrolling should only be in a downward motion). After lots of iterations, this is my workflow when I go to write in Node.js.

Create a New Directory

I keep everything in ~/Documents/Projects, and create a new directory. Sometimes I browse my Projects folder and don’t remember what things are from the name. I suppose this isn’t exactly unique in the code world, though…

Run npm init

Inside of my new directory, the first thing I do when starting a new command line node project is to run npm init.

This command starts a utility that creates a package.json file for the project. When you run it, you’ll be prompted for the answers to several different questions. Hitting enter will accept the default, which is fine. The only thing I change is setting the entry point to src/index.js. If you hit enter too fast, you can always manually edit the package.json file later.

Create the src Directory

Next I create the src folder with mkdir src. I like to put my source code in this directory to avoid having the node_modules directory indexed when I’m using my editor later. I also run touch src/index.js to create a placeholder for the file. If I’m writing a program that has output, I’ll also create an output directory in the root of the project.

Starting Version Control

Even if I’m not planning on uploading my code to GitHub, I typically will start tracking by running git init in the root of my project. This will create an empty repository so you can start tracking changes. If you decide to add a GitHub repo later, you can edit the git config to get it set up.

When creating a new repository on GitHub, I initialize it without a README or .gitignore file in favor of doing them myself manually later.

To add a GitHub repo to the project later, run

git remote add origin git@github.com:username/repo-name.git

Adding a .gitignore File

I typically add a .gitignore file that contains the following:

node_modules/
.env

Start Writing Code

From here, I open up src/index.js and start hacking!

Check out my other articles, or sign up for my newsletter:

No spam. Just code stuff, unsolicited music recommendations, etc.