Skip to content

Instantly share code, notes, and snippets.

@h3ct0rjs
Last active April 23, 2019 13:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save h3ct0rjs/25658e3ebc81866fe83a59f49fe518cf to your computer and use it in GitHub Desktop.
Save h3ct0rjs/25658e3ebc81866fe83a59f49fe518cf to your computer and use it in GitHub Desktop.

Notes

nodejs owns global objects as the following in javascript:

console.log()

setTimeOut() # set a timer delay in the client, server, browser
clearTimeOut()

setInterval() # repeatelly call a delay or some method
clearInterval()

you can access to the global properties in node using the preffix global e.g global.setInterval(), all the variables are not added to the global object, like in the browser that you use window.variablename . Always in node when you define a variable, that variable is part of a module which is only private, you can check this doing console.log(global.module)

> console.log(global.module)
Module {
  id: '<repl>',
  exports: {},
  parent: undefined,
  filename: null,
  loaded: false,
  children: [],
  paths:
   [ '/home/h3ct0rjs/repl/node_modules',
     '/home/h3ct0rjs/node_modules',
     '/home/node_modules',
     '/node_modules',
     '/home/h3ct0rjs/.node_modules',
     '/home/h3ct0rjs/.node_libraries',
     '/home/h3ct0rjs/.nvm/versions/node/v10.15.3/lib/node' ] }
undefined

So lets asume that we have two files app.js and algo.js. We want to use all the methods and variables located in algo.js In order to do that, you will need to expose those definitions, exporting or becoming them public to other modules, for my case app.js.

If you are using es6 you can use :

export default router;

If you are using es5 you can use :

module.exports = router;

using the proper import statement depends in the es implementation, if you check in es5 we had:

const myImport = require('./pathtomodule')

in es6 :

import myImport from './pathtomodule'

also if you want specific things from the imported module you can do :

import {x, y, z} from './pathtomodule';

There are other cool things in the mzdn article but you can use this.

It's prefered to use the es5 syntax due to nodejs support this natively, with es6 you will need to use babel and other that complicates all the development.

Express

If you don't want to handle manually the http server and request object the best way to create http service is using express

express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications

A basic application look like this :

const express = require('express');
const app = express();
const port = process.env.PORT || 3000 ;
app.get('/', (req, res) => res.send('Hello World!'));
app.listen(port, () => console.log(`Example app listening on port ${port}!`))

One note to write is that you're going to be able to create something call middlewares, you can manipulate the request and response cycle, in other words a middleware function is a function that takes a request object and either terminates the request/response cycle or passes control to another middleware function.

Express has a few built-in middleware functions:

  • json(): to parse the body of requests with a JSON payload
  • urlencoded(): to parse the body of requests with URL-encoded payload
  • static(): to serve static files
  • You can create custom middleware for cross-cutting concerns, such as logging, authentication, etc.
// Custom middleware (applied on routes starting with /api/admin) 
app.use(/api/admin’, function(req, res, next)) {     
// ...     
        next(); 
    }

Asynchronous Patterns

There in total 3 ways to handle asynchronous code in nodejs they are :

  • callbacks
  • promises
  • async await
console.log('Antes');
const user = getUser(1, (user)=>{
    console.log(user.gitHubUser);

    //Get Github Repos
    getRepos(user.gitHubUser,(repos)=>{
        for(r in repos) console.log(repos[r])
    })
});
console.log('Despues'); 

// Patterns for Asynchronous Code. 
//  callbacks 
//  promises 
//  async/await 

// Simulate a db connection
function getUser(id, callback){
    setTimeout(()=>{
        console.log('Reading Database!');
        callback({id :id, gitHubUser:"H"})
    },2000);

}

function getRepos(username, cb){
    setTimeout(()=>{
        console.log('Getting Github Repos');
        if(username === 'H'){
            cb(['repo1', 'repo2', 'repo3']);
        }
        else{
            cb([]);
        }
    },4000);
    
}

Is it possible to use Promises. Basically a promise is an object that helps you to control the async execution, a promise is going to promise you the fullfiled/resolved or rejected of the execution.

A promise is an object that receive a function with a couple of parameters that are functions.

const p = new Promise((resolve, reject)=>{ 
    // you async job. 
    // do a get request, connect to a database, and so on. 
    if(result){
      resolve(result);
    }
    else{
    reject(new Error('Error message'));
    }
})

When you create this object, the variable p will have two available methods that are:

  • then
  • catch

If the promise is resolved it's going to return the value and the then is executed, otherwise catch is going to be executed.

console.log('Antes');
getUser(1)
    .then(user => getRepos(user.gitHubUser))
    .then(repos => {for(r in repos) console.log(repos[r]);})
    .catch(err=> console.log(err));
console.log('Despues'); 

// Simulate a db connection
function getUser(id){
    return new Promise((resolve, reject) =>{
        // async job
        setTimeout(()=>{
            console.log('Reading Database!');
            resolve({id :id, gitHubUser:"H"});
    },2000);
    })
}

function getRepos(username){
    return new Promise((resolve, reject) => {    
        setTimeout(()=>{
            console.log('Getting Github Repos');
            if(username === 'H'){
                resolve(['repo1', 'repo2', 'repo3']);
            }
            else{
                reject(new Error('Error no hay repositorios'))
            }
        },4000);
        
    });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment