Getting Started with Node.js

Adapted from Node Hero


Install Node.js

nvm install 4.4
And verify:
nvm --version
And start:
nvm use 4 or nvm use 5
npm install modules:

npm install @myorg/mypackage --save-dev or npm install mocha --save-dev or npm install angular --save

Generate package.json with '''npm init'''. It should look something like:
  {
    "name": "node-project",
    "version": "1.0.0",
    "description": "Beginner node project ",
    "main": "index.js",
    scripts": {
      "start": "node index.js",
      "test": "mocha test",
      "your-custom-script": "echo npm"
    }
    "author": "ddavis",
    "license": "ISC",
    "dependencies": {
      "@myorg/mypackage": "^1.0.0",
      "angular": "^1.5.5",
      "express": "^4.13.4",
      "express-handlebars": "^3.0.0",
      "lodash": "^4.10.0",
      "request-promise": "^3.0.0"
    },
    "devDependencies": {
      "mocha": "^2.4.5"
    }
  }
Create a .gitignore files
  ```
  # Logs
  logs
  *.log
  npm-debug.log*

  # Runtime data
  pids
  *.pid
  *.seed

  # Directory for instrumented libs generated by jscoverage/JSCover
  lib-cov

  # Coverage directory used by tools like istanbul
  coverage

  # node-waf configuration
  .lock-wscript

  # Compiled binary addons (http://nodejs.org/api/addons.html)
  build/Release

  # Dependency directories
  node_modules

  # Optional npm cache directory
  .npm

  # Optional REPL history
  .node_repl_history
  ```
Create index.js, to be used with '''npm start''' command:
  // index.js
  require('./app/index')  

Structure notes

Most Node.js frameworks don't come with a fixed directory structure and it might be challenging to get it right from the beginning. In this tutorial, you will learn how to properly structure a Node.js project to avoid confusion when your applications start to grow.

There are a lot of possible ways to organize a Node.js project - and each of the known methods has their ups and downs. However, according to our experience, developers always want to achieve the same things: clean code and the possibility of adding new features with ease.

In the past years at RisingStack, we had a chance to build efficient Node applications in many sizes, and we gained numerous insights regarding the dos and donts of project structuring.

We have outlined five simple guiding rules which we enforce during Node.js development. If you manage to follow them, your projects will be fine:

  • Rule 1 - Organize your Files Around Features, Not Roles

Imagine, that you have the following directory structure:

  // DON'T

  ├── controllers
  |   ├── product.js
  |   └── user.js
  ├── models
  |   ├── product.js
  |   └── user.js
  ├── views
  |   ├── product.hbs
  |   └── user.hbs

The problems with this approach are:

  • to understand how the product pages work, you have to open up three different directories, with lots of context switching,
  • you end up writing long paths when requiring modules: require('../../controllers/user.js')
  • Instead of this, you can structure your Node.js applications around product features / pages / components. It makes understanding a lot easier:

    // DO
    
    ├── product
    |   ├── index.js
    |   ├── product.js
    |   └── product.hbs
    ├── user
    |   ├── index.js
    |   ├── user.js
    |   └── user.hbs
    

Rule 2 - Don't Put Logic in index.js Files

Use these files only to export functionality, like:

  // product/index.js
  var product = require('./product')

  module.exports = {  
    create: product.create
  }

Rule 3 - Place Your Test Files Next to The Implementation

Tests are not just for checking whether a module produces the expected output, they also document your modules (you will learn more on testing in the upcoming chapters). Because of this, it is easier to understand if test files are placed next to the implementation.

Put your additional test files to a separate test folder to avoid confusion.

  .
  ├── test
  |   └── setup.spec.js
  ├── product
  |   ├── index.js
  |   ├── product.js
  |   ├── product.spec.js
  |   └── product.hbs
  ├── user
  |   ├── index.js
  |   ├── user.js
  |   ├── user.spec.js
  |   └── user.hbs
  Rule 4 - Use a config Directory

To place your configuration files, use a config directory.

  .
  ├── config
  |   ├── index.js
  |   └── server.js
  ├── product
  |   ├── index.js
  |   ├── product.js
  |   ├── product.spec.js
  |   └── product.hbs

Create a separate directory for your additional long scripts in package.json

  .
  ├── scripts
  |   ├── syncDb.sh
  |   └── provision.sh
  ├── product
  |   ├── index.js
  |   ├── product.js
  |   ├── product.spec.js
  |   └── product.hbs

Databases


Storing data in a global variable

If a user wants to sign up for your application, you might want to create a route handler to make it possible:

  const users = []

  app.post('/users', function (req, res) {  
      // retrieve user posted data from the body
      const user = req.body
      users.push({
        name: user.name,
        age: user.age
      })
      res.send('successfully registered')
  })

Using this method might be problematic for several reasons:

  • RAM is expensive,
  • memory resets each time you restart your application,
  • if you don't clean up, sometimes you'll end up with stack overflow.

If we store our user data permanently on the file system, we can avoid the previously listed problems.

  const fs = require('fs')

  app.post('/users', function (req, res) {  
      const user = req.body
      fs.appendToFile('users.txt', JSON.stringify({ name: user.name, age: user.age }), (err) => {
          res.send('successfully registered')
      })
  })

Unfortunately storing user data this way still has a couple of flaws:

  • Appending is okay, but think about updating or deleting.
  • If we're working with files, there is no easy way to access them in parallel (system-wide locks will prevent you from writing).
  • When we try to scale our application up, we cannot split files (you can, but it is way beyond the level of this tutorial) in between servers.

results matching ""

    No results matching ""