Skip to main content

2 posts tagged with "nodejs"

View All Tags

· 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!');              }            });        });

· 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..