Evbogue.com


Node.js and JavaScript basics

By Ev Bogue - April 28th 2016

Getting started with Node.js can be a skill leap for most computer users. We live at the end of the cloud age. Having a basic understanding of how to get Node.js up and running in order to code in basic JavaScript is a useful skill for almost any computer user, because being able to code will give you a larger appreciation for what can be done with computers.

Even if you don't code major advancements for humans and technology, at least you're getting code running in your own machine. From there you can edit json config files, or perhaps build a site out using Metalwork.

There are two primary JavaScript experiences. The first has been around for a long time: using JavaScript in the browser.

The second is a more recent innovation: using JavaScript on your local machine or a web server with Node.js.

There are three steps to getting started with Node.js

1. Install Node.js and npm

Node.js is a program that runs the V8 JavaScript engine on your system. Once you have Node.js installed, you can use npm to install libraries available at npmjs.org.

To install Node.js follow the instructions available at the Node.js website for your system.

Depending on what kind of system you're running, the instructions will differ. If you're using Windows or a Mac, then the installer will seem to be the intuitive way to do things. If you're running Linux then you'll be familiar with using a package manager to install programs, and your install will look more similar to typing

% sudo pacman -S nodejs npm

Which is how Node.js is installed on an Arch Linux system using Pacman.

2. Test that you've installed Node.js

Once you have Node.js installed, open up a Terminal application and type

% node -v
v6.0.0

Which should return the version of Node.js you've installed.

3. Build a basic "hello world" server

Next create a web server using Node.js and visit it using your web browser.

The current example from the Node.js website looks this way:

const http = require('http');

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

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

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

Type this server example out in a file called helloworld.js and run it using the command

% node helloworld.js
Server running at http://127.0.0.1:3000/

Navigate your web browser to http://127.0.0.1:3000/ and you'll see the words "Hello World" on your screen.

That's it, you're now free to program more advanced programs in Node.js!

The basics of distributed Git →

← Gogs for self-hosted Git

git

This is Decent: ?


about | blog | ssb | decent | ev@evbogue.com | gitmx