Skip to content

Instantly share code, notes, and snippets.

@danilobatistaqueiroz
Last active May 24, 2019 20:16
Show Gist options
  • Select an option

  • Save danilobatistaqueiroz/f2ec22e1aed912e6dd8586b2dd979e48 to your computer and use it in GitHub Desktop.

Select an option

Save danilobatistaqueiroz/f2ec22e1aed912e6dd8586b2dd979e48 to your computer and use it in GitHub Desktop.
topics about nodejs

an important aspect of let is that a variable declared using it is only available in the block scope in which it was defined.
var is function scoped, not block scoped, and shouldn't be used in ES6 now that you have const and let at your disposal.

Requires are run synchronously by Node.js. If they are called from within a function, it may block other requests from being handled at a more critical time.

Prefer the strict equality operator === over the weaker abstract equality operator ==

node.js is designed to be asynchronous. So, any function which does blocking input/output (I/O), such as reading from a socket or querying a database, will take a callback function as the last parameter, and then continue with the control flow, only returning to that callback function once the blocking operation has completed.

Let’s look at the following simple example to demonstrate this.

function foo() {
    someAsyncFunction(params, function(err, results) {
        console.log(“one”);
    });
    console.log(“two”);
}

In the above example, we may think that the output would be:

one two

but in fact it might be:

two one

.

installing node
you can install using: Chocolatey for Windows
or simply downloading the zip file and configuring the %PATH% environment variable
apt-get for Ubuntu

initiating a new project
$ npm init
will create a file package.json based on your chose options

installing all modules from package.json
Having a package.json in the root. To install all the dependencies in a specific node_modules directory. run: $ npm install

debugging with node-theseus
https://github.com/adobe-research/theseus
npm install -g node-theseus
In Brackets, click the menu item File > Extension Manager... Type "Theseus" in the search box. Click the "Install" button Start your program by running: node-theseus app.js

debugging using vscode

body-parser
Express doesn’t handle reading data from the <form> element on it’s own. We have to add another package called body-parser to gain this functionality.

installing body-parser and saving it in package.json:
npm install body-parser --save

cookie-parser − Parse Cookie header and populate req.cookies with an object keyed by the cookie names.

multer − This is a node.js middleware for handling multipart/form-data.

nodmon
nodmon will help us to keep track of changes to our application by watching changed files and automatically restart the server

installing nodemon only for development environment
npm install --save-dev nodemon
calling nodemon installed only locally:
$ ./node_modules/.bin/nodemon server.js
That’s a handful to type. One way to make it simpler is to create a script key in package.json

{
  // ...
  "scripts": {
    "dev": "nodemon server.js"
  }
  // ...
}

Now, you can run npm run dev to trigger nodemon server.js

installing nodemon globally (the use of the global installations is discouraged)
npm install nodemon -g

express:
Express é um framework web mvc para Node.js. Ele é minimalista, flexível e contém um robusto conjunto de recursos para desenvolver aplicações web, como um sistema de Views, estrutura MVC, um robusto sistema de roteamento, um executável para geração de aplicações e muito mais.

In Express.js, we create an “application” (app). This application listens on a particular port for HTTP requests to come in. When requests come in, they pass through a middleware chain. Each link in the middleware chain is given a req (request) object and a res (results) object to store the results. Each link can choose to do work, or pass it to the next link. We add new middleware via app.use(). The main middleware is called our “router”, which looks at the URL and routes each different URL/verb combination to a specific handler function.

mustache:

mongoose:

it is a ODM
elegant mongodb object modeling for node.js
Mongoose provides a straight-forward, schema-based solution to model your application data. It includes built-in type casting, validation, query building, business logic hooks and more, out of the box.

sequelize:

passport:

starting the server:
npm run start


Como surgiu o NodeJs

As everybody can see from the first presentation of Node.js in 2009, Ryan Dahl, the creator of Node.js, criticized:

  • The limited possibilities of the most popular web server in 2009, Apache HTTP Server to handle a lot of concurrent connections (up to 10,000 or more);
  • The most common way of creating code (sequential programming), when code either blocked the entire process or implied multiple execution stacks (read as “more hardware and software”, more money) in the case of simultaneous connections.

As Ryan Dahl noted, Node.js and Javascript were able to solve this problem at that time at no extra cost:

O nodeJs é uma tecnologia concorrente assincrona

Node.js provides a purely evented, non-blocking infrastructure to script highly concurrent programs. Javascript is designed specifically to be used with an event loop: anonymous functions, closures; only one callback at a time; I/O through DOM event callbacks. The culture of JavaScript is already geared towards evented programming.

Ryan Dahl‘s presentation was regaled with ovations. One of the most common web applications' performance problems was resolved! No additional hardware! No additional monthly hosting costs! The only strict requirement was retraining programmers to teach them using event loops, callbacks, and non-blocking I/O.

NodeJs é single thread

The disadvantages of being single-threaded: your code will run in single thread only and so you can’t do anything complicated. If your code needs to process data for each request and it’s going to take just 10 milliseconds and there are 1000 concurrent connections, it will take 10 seconds to finish all of them. It’s pretty bad response time, isn’t it?

PHP e Nodejs
I use Node.js for tasks involving big data flows and PHP for tasks involving complex logic, high-load tasks, for dealing with external utilities, applications, and OS. PHP has a lot of different libraries, frameworks, and it is more standardized than Node.js (however, Node.js is not far behind and continues to gain momentum). I

links: https://belitsoft.com/php-development-services/php7-vs-nodejs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment