Node.js & Git Cheat Sheet

$git config --global init.defaultBranch main   New projects use main

Start a new Node.js project

$mkdir <project dir>
$cd <project dir>
$git init
$git remote add origin git@github.com:<user>/<repo>.git
$vim .gitignore
node_modules/
<server dir>/secrets
<server dir>/data
<server dir>/logs
.work
$mkdir <project dir>
$npm init -y        Create a package.json with default values
$npm install <packages>
$vim package.json   Set type module, if *.js files use import
// Comment
{
  "name": "<project name>",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "copy(l)eft"
}
$git add .
$git reset   undo add
$git commit -m "Initial commit"
$git push -u origin main

Install a small HTTP server using built-in http module

// import * as http from "http";
const http = require('http');
const server = http.createServer((req, res) => {
	res.write('Hello, World!');
	res.end();
});
server.listen(<port number>, () => {
	console.log('Server running at http://localhost:3000/');
});

Use GIT

Initialize Git & Connect to GitHub

$git init                        Initialize git in the project folder
$git remote add origin https://github.com/username/repository-name.git
$git add .                       Stage all files for commit
$git commit -m "Initial commit"  Commit files
$git push -u origin main         Push to GitHub (assuming 'main' is the default branch)
Commit & Push to GitHub
$git add .                             Stage changes
$git commit -m "your commit message"   Commit changes
$git push origin main                  Push to GitHub (replace 'main' with your branch name if different)
Branching (to try out new changes)
$git checkout -b new-branch-name   Create and switch to a new branch

Make new changes in the new branch, then either delete or merge:

To discard the branch (revert all changes):
$git checkout main                          Switch back to main
$git branch -D new-branch-name              Delete the branch locally
$git push origin --delete new-branch-name   Delete the branch from GitHub
To merge the branch and make changes permanent (no conflicts):
$git checkout main           Switch to main branch
$git merge new-branch-name   Merge the changes from the branch
$git push origin main        Push the updated main branch to GitHub

Additional Tips for Conflict-Free Merging:

Make sure your branch is up-to-date with the main branch before merging:
$git checkout main
$git pull origin main
$git checkout new-branch-name
$git rebase main   Rebase your branch onto main to ensure there are no conflicts