Node.js

Node.js is a JavaScript runtime environment that lets JavaScript run outside the browser. Node.js lets developers create servers, web apps, command line tools and scripts - all outside the browser.

Node.js Basics

node Commands

  • node - Enter into a node runtime environment in the terminal.
  • node (-v) - See what version of node is installed.

nvm Commands

Node Version Manager (NVM) is a tool for downloading and installing Node.js.

  • nvm (-v) - See what version of nvm is installed.
  • nvm install (node / 8.10.0) - Install the latest version of node, or a specific version.
  • nvm use (node / 8.10.0) - Use the latest version of node, or a specific version.
  • nvm run (8.10.0) (app.js) - Run a file with a specific version of node.
  • nvm alias (default) (node / v24.0.1) - Create a shortcut for a specific version of node.

npm Commands

Node Package Manager (NPM) is the standard package manager for Node.js. NPM installs, updates, and manages downloads for dependencies. Dependencies are pre-built pieces of code, such as libraries and packages, that a Node.js application needs to work properly.

  • npm init (-y) - Initialize node in a directory. The -y flag accepts default values.
  • npm install (package_name) - Install all dependencies in the package.json file, or only specified ones.
  • npm update (package_name@version#) - Update all dependencies in the package.json file, or only specified ones (with a specified version number).
  • npm uninstall (package_name) - Uninstall all dependencies in the package.json file, or only specified ones.

npx Commands

Node Package Execute (NPX) executes Node.js packages directly from the registry without needing to install them globally.

  • npx create-react-app - Creates a React.js app.

Node Examples

Running JavaScript Outside the Browser

touch node_script.js
function greet(name) {
  console.log(`Hi there ${name}, welcome to NodeJS!`);
}

greet('Grant');
node node_script.js

Creating a Simple Server

touch server.js
const { createServer } = require('node:http');

const hostname = '127.0.0.1';
const port = 3000;

const server = createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
node server.js

Child Process

const { exec } = require('child_process');

exec('zsh /Users/grantdavis303/desktop/project_dashboard.sh grants_dev_tools', (err, stdout, stderr) => {
  if (err) return res.send(err.message);
  res.send(stdout);
})