My First Node Project

Tools we'll use

  • CLI (Command Line)
  • npm (Node's Package Manager)
  • git (version control: See separate presentation)

Create the project directory and files

  • mkdir sites && cd sites <-- in a sensible place, like your user directory (DO THIS THE FIRST TIME ONLY)
  • mkdir <project name>
  • cd <project name>
  • mkdir any directories you need
  • touch <filepath/name1> <filepath/name2>, etc.
  • code .

 

Once your file and directory structure are complete, it's time to initialise it as a node project, using npm

npm

  • npm is node's package manager
    • packages are 3rd party software
    • npm init [-y if you can't be bothered to answer the questions]
  • You install scripts by typing npm install <package>
    • so for example npm install lodash
  • The plan behind most package managers is:
    • To allow easy installation/update
    • To keep software up-to-date (security)
    • To resolve dependencies for 3P software
    • To keep projects lightweight
  • A list of all available software is can be found at https://www.npmjs.com/
  • (npm had a competitor bower.io for front-end packages - it's dying. Let it...)

Yarn

  • Yarn is a competitor to npm
  • Yarn belonged to facebook and was opensourced in 2016
  • It is compatible with the npm registries (i.e. it downloads the same 3rd party packages)
  • Features:
    • Unlike npm, yarn keeps a record of what you download, so if you've installed a package in another project yarn will copy it across, thus increasing your build times
    • syntax is more terse (yarn, rather than npm i; yarn <op> rather than npm run <op>, etc.)
  • You can install with npm [ironically] or homebrew
  • Docs
  • Don't mix the two. If i were you I'd run

package.json

  • package.json where npm keeps track of which software you installed
  • This means that when you put code in a repo you don't have to keep the 3rd party software with it
    • When you clone the project do npm install and all the 3rd party software is downloaded for you
  • When you npm install a package, it saves it for you in the dependencies
    • dependencies are what's required for your program to run at run-time
    • devDependencies are what is required to build your project (think optimising, testing, etc.)
      • Needs -D flag record as devDep
        • npm install mocha -D

Dependencies

  • dependencies
    • used by the actual software
  • devDependencies
    • used in optimising/testing/producing your javascript program
  • peerDependencies
    • optional
    • used to enhance the 3P software you use

Two Cousins of package.json

  • As node grew older, we realised that the range of versions we were allowing for software was too big, so we locked it down to narrower versions
    • The first version of this lock file was 'shrinkwrap.json' (created by typing npm shrinkwrap)
    • The new version is package.lock.json (auto-generated)
    • Do not alter these files manually!

Getting started with NPM

  1. With your command line pointer inside your main project directory, type npm init
  2. Answer the questions (or do npm init -y)
  3. Some packages you'll want to use for various projects, like gulp, or trash-cli
    1. Install them globally: npm install -g <package>
    2. If you use the in a project, remember to list it locally
    3. npm will look locally first, then globally, then error...
  4. Now you can install software npm install [-D] <package>
    1. npm i is an alias for npm install
    2. -D installs as a devDependency
  5. Software versioning uses the Semantic Versioning (SemVer) approach

SemVer (Semantic Versioning)

  • e.g. 3.4.1
    • <major>.<minor>.<patch>
      • Major: Significant changes - will likely break your program (without update work from you)
        • method names change; methodology, etc.
      • Minor: May break your program (probably not)
      • Patch: Really should have no impact (like renaming variables, or refactoring)
    • Full range guide

Full list of npm commands

Create your first .js file

  • create a file called server.js
  • add console.log('hello world!'); to it
  • With your CLI pointer in its parent directory, type npm start
  • Time to use your skillz, Ninjas!! 

Using 3rd Party Packages

  • Finding:
  • Install in your project
    • npm i <packageName>
      • -D if devdependancy
    • At the top of your code file
      • var <packageName> = require('<packageName>');
    • Then in code
      • <packageName>.someFn(....);

Environment Variables

  • Running node is a 'process' (pid)
  • The process is available in the injected variable process
  • The process has a lot in, but also has the ability for you to inject variables depending on the system
    • So the same script runs on different servers.
    • It connects not to 'mongodb://jaskldjfkls' but instead to process.env.<variable_name> (a variable name you decide)
    • server1 would point1 at db 1; server2 maybe at db2

Environment Variables

  • As well as allowing us to pass configuration separately from programming (which allows automation), we can also pass secrets
  • You don't want to hard-code your password into your scripts, otherwise people could steal them, so we do this:
const Twitter = require('twitter');

const { consumer_key, consumer_secret, access_token_key, access_token_secret } = process.env;
 
const client = new Twitter({
  consumer_key,
  consumer_secret,
  access_token_key,
  access_token_secret, // es6 trailing comma
});

Passing in Environment Variables

  • To pass the variables in remotely, you'd use either the hosting interface or a CLI (Command-line Interface/tool)

Passing in Environment Variables

  • To pass the variables in locally, you'd use a package like dotenv
  • .env file:
DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3
  • js file
// Put at top of file to put the variables in the process
require('dotenv').config();

// Use them...
const db = require('db')
db.connect({
  host: process.env.DB_HOST,
  username: process.env.DB_USER,
  password: process.env.DB_PASS
})

NPM Scripts

  • npm has the ability to run some shell scripts
  • npm install you've met
  • npm start will run node server.js
  • npm start and npm test are auto
    • for custom (inc. build) npm run <task name>
  • You can define your own in package.json
    • note variable insertion in npm start here:
{
  "scripts": {
    "dev": "nuxt && functions:build && functions:serve",
    "build": "nuxt build",
    "start": "MY_VAR=2 nuxt start",
    "start:production": "nuxt build && nuxt start",
    "generate": "nuxt generate && npm run functions:build",
    "functions:serve": "netlify-lambda serve lambda",
    "functions:build": "netlify-lambda build lambda"
  }
}

My First Node Project

By James Sherry

My First Node Project

  • 1,137