Skip to content

Instantly share code, notes, and snippets.

@shafayeatsumit
Last active March 28, 2018 15:07
Show Gist options
  • Save shafayeatsumit/81a92a53f6e99db6b6e50df733c195c7 to your computer and use it in GitHub Desktop.
Save shafayeatsumit/81a92a53f6e99db6b6e50df733c195c7 to your computer and use it in GitHub Desktop.
In an effort to learn node js .This gist consists of some code snippets and small chunk texts that helped me to learn node.

Learn Me Node

A Node.js application involves following 3 steps :

  • Import required modules − We use the require directive to load Node.js modules.
  • Create server − A server which will listen to client’s requests similar to Apache HTTP Server.
  • Read request and return response − The server created in an earlier step will read the HTTP request made by the client which can be a browser or a console and return the response.

http server

const http = require('http');

const hostname = '127.0.0.1';
const port = 3333;
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 + '/');
});

eslint setup and configuration

We want to install the Node.js package eslint-config-airbnb-base as a development dependency, but it has some peer dependencies (have to be manually installed along with it). To inspect these dependencies we type:

npm info "eslint-config-airbnb-base@latest" peerDependencies

and see that we also need to install eslint and eslint-plugin-import. We use the following commands to install all three development dependencies.

npm install --save-dev eslint
npm install --save-dev eslint-plugin-import
npm install --save-dev eslint-config-airbnb-base

Additionally, ESLint needs to be configured using an .eslintrs.js file.

module.exports = {
  extends: [
    'airbnb-base',
  ],
  plugins: [
    'import',
  ],
  env: {
    node: true,
  },
};

With all this in place, we can lint our index.js file.

./node_modules/.bin/eslint index.js

  • We can simplify running the linter by editing package.json.
...
"scripts": {
  "lint": "eslint index.js",
  "test": "echo \"Error: no test specified\" && exit 1"
},
...

npm run lint

  • to remove console warning in slint /* eslint-disable no-console */

List of blog posts for learning:

Build a Node.js API in Under 30 Minutes

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