Skip to main content

· 2 min read
Kumar Nitesh

Beginner guide to connect to MySQL with NodeJS

Start a Node JS project

> mkdir nodejs-mysql> cd nodejs-mysql> npm init -y

install mysql package

> npm i --save mysql

create a server.js file

> touch server.js

Open nodejs-mysql in your favorite editor and add following code to server.js

const mysql = require('mysql')
// create connection object for DB, you can get all below values from the connection stringconst connectionConfig = {    host: '<replace_with_your_db_server>', // if mysql is running locally it may be 'localhost'    user: '<replace_with_user_id_having_access_to_your_db>',    password: '<replace_with_db_password>',    database: '<default_database_to_connect>'}// initialize with connection configconst db = mysql.createConnection(connectionConfig)
// connect to the serverdb.connect(function(err){    if(err) throw err    console.log("MySQL DB connected successfully!")})
// create query for your dbconst sql =`select * from dbName.tableName`;
// query your db    db.query(sql, function(err,result){        if(err) throw err        console.log(result)        Object.keys(result).forEach((key)=>{            console.log(result[key])            })    })

    // don't forget to close your connection    db.end(err=>{        if(err) throw err        console.log('Connection to MySQL is successfully closed')    })}

To run code, run below command in terminal

> node server.js

You should see the result of your query in the terminal. To save query result in a file you can use csv-stringify package. Here is small code snippet for the same

...const fs = require('fs');const stringify = require('csv-stringify');......
// queryResult is a string value filtered after querying databasestringify(queryResult, function(err, output) {            fs.writeFile('query.csv', output, 'utf8', function(err) {              if (err) {                console.log('Some error occured - file either not saved or corrupted file saved.');              } else {                console.log('It\'s saved!');              }            });        });

· One min read
Kumar Nitesh
// fetching data from an API with basic promise syntax (notice the use of arrow functions)window  .fetch("http://jsonplaceholder.typicode.com/posts")  .then((response) => response.json())  .then((data) => console.log(data));
// fetching same data from API with async/await    async function getPostData() {         const response = await window.fetch( "http://jsonplaceholder.typicode.com/posts" );        // we need to resolve two promises using await to get the final data         const data = await response.json();         console.log(data);     }     getPostData();

· One min read
Kumar Nitesh

If you have not added Prettier and ESlint into your project you are missing a lot of out of box configuration and code formatting.It's simple to add them and follow industry based best practice and adding them will not even take 2 minutes.

So here are the steps to add them into your project.

  • Add Prettier as an extension to your VSCode, or if you not using VSCode install it globally using npm i -g prettier

  • Add ".prettierrc" file to your project root directory

  • Add following code into ".prettierrc"

{ "semi": false, "trailingComma": "all", "singleQuote": true, "printWidth": 70 }

Add followig two packages to your project

npm install --save-dev eslint-config-prettier eslint-plugin-prettier

Add .eslintrc.json

Add following code to ".eslintrc.json"

{  "extends": ["prettier"],  "plugins": ["prettier"],  "rules": { "prettier/prettier": ["error"] }}

Thats it, your project to s configured to use best practices based on Prettier and ESLint.

Read about Prettier here

Read about ESlint here

Here is AirBnb eslint config: https://www.npmjs.com/package/eslint-config-airbnb

Happy Coding... Kumar

· 2 min read

Follow below steps to run a HTTPS server for your nodeJs app. To run your nodesJS + ExpressJs app on HTTPS, you need to first create a SSL certificate. To do so we will use openssl. Run below command on your terminal

openssl req -x509 -newkey rsa:2048 -keyout keytmp.pem -out cert.pem -days 365

Run below command on same terminal after cert.pem and keytmp.pem has been generated

openssl rsa -in keytmp.pem -out key.pem

Include your keys and certificatio to your app by moving them to appropraiate folder

Once you have all files in right place, update your server.js/index.js file for ExpressJS, as shown below

import express from 'express'; import https from 'https import fs from 'fs'
const port = process.env.PORT || 3003;
const key = fs.readFileSync('./server/key.pem') const cert = fs.readFileSync('./server/cert.pem'),
// we will pass our 'app' to 'https' server const server =https.createServer({ key: , cert: passphrase: 'Your Pass phrase' },app);
app.get('/', (req, res) => { res.send('This is an secure server') });
server.listen(port, () => { console.log('listening on 3003') });

Now if you run your app you can navigate to https://localhost:3003, your browser will throw a long message warning about validatiy of the SSL certificate, since it has been genrated locally by you and not generated by a Standard Certificate issuer. You can igmore and Click on continue to run your server on HTTPS.

~Happy Coding..

· One min read
Kumar Nitesh

So, on daily basis after working on a big feature and after creating PR, my PR builds fails(yes we have CI/CD built in). Most of the time the reason for fail is linting issue but sometime it's Merge Conflict. I used to rebase the traget branch and resolve merge conflict, but this used to recreate all the commits that I had done, just creating duplicate commits. Recently I came across a better way of resolving PR merge conflict.

Let's assume we are working on feature/branch-that-needs-to-be-merged and our working branch has created a PR against main-development-branch. The PR autobuild has failed due to merge conflict and you need to resolve this merge conflict. To resolve

checkout main-development-branch get latest checkout feature/branch-that-needs-to-be-merged get latest and then run git pull origin main-development-branch

It will display Merge conflict, resolve your merge conflict, commit and push feature/branch-that-needs-to-be-merged. Now your PR will not show any merge conflict and build will also pass. Given now you have all check pass for a succesfull merge you can go ahead and merge you code.

~ Happy coding

· 2 min read
Kumar Nitesh

Most beginner like me will have a bit of confusion about when to use state and when to use props, which component should have its own state or rely on props and how to go about it all.

Both state and props hold information, but they are different. The props are immutable, whereas the state is not. Typically, the child component receives the props variables from parents. They store the props variables in the state as they can’t modify props values. They take in read only copy and use it only to render the view of the component. Even the actons can be passed to children in the form of props, and if any event affects the parent’ state, the child calls that action(method) which is defined in parent.

Anything that can change due to an event anywhere in the component hierarchy qualifies as being part of the state. Avoid keeping computed values in the state; instead simply compute them when needed, typically inside the render() method.

Do not copy props into a state, just because props are immutable. If you feel the need to do this, think of modifying the original state from which these props were derived. One exception is when props are used as initial values to the state, and the state is truly disjoined from the original state after the initialization.

· One min read
Kumar Nitesh

A simple example of creating an ErrorBounday component and using in your application.

class ErrorBoundary extends React.Component {  constructor(props) {    super(props);    this.state = { hasError: false };  }
  static getDerivedStateFromError(error) {    // Update state so the next render will show the fallback UI.    return { hasError: true };  }
  componentDidCatch(error, info) {    // You can also log the error to an error reporting service    logErrorToMyService(error, info);  }
  render() {    if (this.state.hasError) {      // You can render any custom fallback UI      return <h1>Something went wrong.</h1>;    }
    return this.props.children;  }}

To use above component import it in your app or in the component file where you want to use it

import ErrorBoundary from./ErrorBoundary’

and wrap your component with the imported component

<ErrorBoundary>  <Your Component /></ErrorBoundary>

· One min read
Kumar Nitesh

To fix Git password after you have changed it in GitHub.com

on macOS, you can use

git config --global credential.helper osxkeychain

Above command will show no output. But a username and password prompt will appear with your next Git action (pull, clone, push, etc.).

For Windows, it’s the same command with a different argument:

git config --global credential.helper wincred

· One min read
Kumar Nitesh

Copy and paste below command in Chrome Developer Tool

console.log('%c React Hooks', 'color: #333; font-weight: bold; font-size: 24px');
console.log('%c Oh my heavens! ', 'background: #222; color: #bada55');