Wednesday 27 December 2017

Capitalizing first letter and replaceAt particular index of String in Javascript

These are the two functions that will help in most cases where we need to replace index of a particular stiring.

Capitalizing first letter of a string can also be done using css property text-transform:capitalize, in many cases such as if we want to show a stirng with first letter capital in title attribute on hover this does'nt work. So this is handy javascript function that will be useful.


//replaceAt index of particluar string

 
function replaceAt(str, index, replacement) {
    return str.substr(0, index) + replacement + str.substr(index + replacement.length);
}


//capitalize first letter of a string

function capitalizeFirstLetter(string) {

    if(typeof string != "undefined" && string != "" && string != "undefined"){

    return string.charAt(0).toUpperCase() + string.slice(1);

    } else {

            return string;

    }

}

Wednesday 6 December 2017

Develop a POST and GET request to add and get data from a file in nodejs

So far, we've learnt developing nodejs API with GET and POST request in json format. Today, let's raise our learning bar and learn saving or writing the json data to a file.

Since, nodejs has huge repository of node modules, it makes our life pretty easy to do almost anything just by importing the respective module.

For instance, in this post, we are going to save the json data to a file for which we need a file stream library that enables us to read and write the data. With nodejs, it is just simple to accomplish this. All you need to do is, install the 'fs' module using npm(Node Package Manager) using following command in terminal:


npm install fs

Similarly, body parser is used to extract the entire body portion of an incoming request stream which is exposed on req.body. You may install it using following command:


npm install body-parser

Let's first add the user data which includes the user name, profession and password. Since, we require the user's input here, let's use POST request to send these parameters.

Here, I am saving the data to a file named users.json

server.js


var express = require('express');

var app = express();

var fs = require("fs");

var bodyParser = require('body-parser');

app.use(bodyParser.json({limit: '5mb'}));//set the limit of maximum request body size

app.use( bodyParser.json() );       // to support JSON-encoded bodies

app.use(bodyParser.urlencoded({     // to support URL-encoded bodies

        extended: true,

        limit: '5mb'

}));

   

//saving the user to file

app.post('/addUser', function (req, res) {

    // First read the parameters sent through body.

    var name = req.body.name;

    var password = req.body.password;

    var profession = req.body.profession;

//creating a JSON object with the received parameters.

    var user = {

        "user1" : {

            "name" : name,

            "password" : password,

            "profession" : profession,

            "id": 1

        }

    }

user = JSON.stringify(user);

fs.writeFile('users.json', user);

        console.log("added");

res.json({'message' : 'User added', 'details' : JSON.parse(user) });

})     


//To list the saved users, here's a GET request


app.get('/listUser', function (req, res) {

    // First read existing users.

    fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {

        data = JSON.parse( data );

        console.log( data );

        res.json(data);

    });

})

// set a port for the server to listen

var server = app.listen(8081, function () {

    var port = server.address().port

    console.log("Example app listening at http://localhost:%s", port)


})

Now let's run the server to save the user data:

node server.js

Example app listening at http://localhost:8081


To insert the data, send a POST request, you may send the data through form-data or use third party REST client apps like REST client, Http Request or Post Master.

I have used a HTML form to add the user



Here's the HTML code :


<html>

<title>Add user</title>

<body>

<form  action="http://localhost:8081/addUser" method="post">

  <input value = "name" type="name" name="name" />

  <input value = "profession" type="profession" name="profession" />

  <input value = "password" type="password" name="password" />

  <input type="submit" value="Add"  name="submit" />

  <input type="reset" value="Clear"/>

</form>

</body>

</html>
Output



Here the data is inserted to users.json file now. To fetch the data from file, we use GET request.

Enter the url "http://localhost:8081/listUser" in your browser and it lists the users in the file.

That's it! Hope this was of help. Happy coding!

Monday 27 November 2017

Make a list element active when included using php include


Often there is a requirement to make a menu element active when we import something using php include. Its quite simple and this is how its done.

<? php include "includes/sidebar.php"; ?>   

(sidebar.php): 

<ul id="sidebar">
  <li><a href="link1.html">Link1</a></li>
  <li><a href="link2.html">Link2</a></li>
  <li><a href="link3.html">Link3</a></li>
  <li><a href="link4.html">Link4</a></li>
</ul>

CSS:

ul#sidebar > li.active {
 background-color:#6495ED;
 color:#fff;
}

Javascript (jQUery solutuion): 


//current url being access
 var cur_href = window.location.href;
 $(document).ready(function(){
  $("#sidebar li a").each(function(){
   //get current href link
   var cur_attr =$(this).attr('href');  
   //save into regex
   var regex = new RegExp(cur_attr,"ig");
   //test if current link and current href matched
   if(regex.test(cur_href)) {
    $(this).parent().addClass('active'); //if yes then addClass 'active'
   } else {
    $(this).parent().removeClass('active'); //else removeClass 'active'
   }
  });
 });

This will make current menu link active in sidebar.

Mongo error "Two many open files", mongod server does'nt start

Solution 1(temporary and tested):

If you're using bash, ulimit -n will only display the soft limit. To get the hard limit, you need to do ulimit -Hn.

On my system, I see this:

$ ulimit -n
1024  

 Set ulimit value to new value as following:
 
 $ ulimit -Hn
4096


ulimit -n <value> (this will only set for current session, better do it in a screen mode and run it in background)

 More info: Here

Solution 2(permanent and not tested):

Modify /etc/security/limits.conf with what you need. Example:

user soft nproc 64000

Restart machine to make the changes effective.

More info: Here

Resolve gedit open issue when opening from remote machine

What happens is  sometimes when we try  to ssh into a system and open gedit in that machine(remote) everything seems fine until we try to  type something or save into that file or even we cannot open other files using Open menu in file tab.

So the solution here is:

Use nautilus/gedit on local machine

1. Open a nautilus file browser window and select "connect to server" from the menu in the top panel.

2. Enter in the server(remote) info (use ssh:// or sftp:// for ssh connections).

3. Enter password and there you go. You will be connected to the remote machine and now your gedit works fine.


Courtesy: this answer from ask ubuntu is where I found the solution.





Friday 17 November 2017

Burn an image file(ISO) to CD/DVD in linux


There are plenty of tools available in open source to burn an ISO file to CD/DVD. But, that has to get you through the hassle of downloading and installing the tools.

In most of  the linux derivatives, you can burn the ISO file to disc in command line itse ilf. All you have to do is execute the following command in your terminal and you are all good to go.


$ growisofs -dvd-compat -Z /dev/sr0=/Path_to_iso_file

Example


$ growisofs -dvd-compat -Z /dev/sr0=/home/user_name/Downloads/LinuxMint.iso

Hope this helps ;)


Monday 6 November 2017

Handling error "You probably tried to upload a file that is too large. Please refer to documentation for a workaround for this limit."


Handling error "You probably tried to upload a file that is too large. Please refer to documentation for a workaround for this limit."

Usually, we come across such errors when we try to import a large file in to mysql through phpmyadmin. This is because there is a pre-defined file limit in php for file upload which is 2MB.

You may change the file upload limit as per your requirement by changing php configuration following the below steps :

1. Navigate to apache2 directory and open php.ini file using vi or vim editor.


root@user-B85M-D3H:~# vim /etc/php5/apache2/php.ini 

2. Change the values of the following lines to as per your requirement.(I am changing the limit to 120 MB here)

&nbsp;upload_max_filesize 120M //file size
&nbsp;post_max_size 120M
&nbsp;max_execution_time 200
&nbsp;max_input_time 200

3. Please ensure that the max_execution_time, max_input_time should always be greater than upload_max_filesize and post_max_size.

4. Once you make the changes, save the file and restart the apache server using the command :

service apache2 restart  

Hope this helps. Happy coding!

Friday 27 October 2017

Developing a POST request in nodejs

Unlike GET request which sends the data through url may not be considered the right option in case of sending a confidential data, POST request is considered the best option as it encrypts the data in the body to send it.

Nodejs is a one of a kind where you can easily create a POST request. Let's learn how to create a POST request.

1. We will create a request to get the user name. Let's name the server file as server.js

server.js

var express = require('express');

var app = express();

var bodyParser = require('body-parser');


// Create application/x-www-form-urlencoded parser

var urlencodedParser = bodyParser.urlencoded({ extended: false })


//The / here represents the path to an interface to send the user name from

    app.get('/', function (req, res) {

        res.sendFile( __dirname + "/" + "index.html" );

    })


app.post('/listUsers', urlencodedParser, function (req, res) {

    // Prepare output in JSON format

    response = {

        first_name:req.body.first_name,

    last_name:req.body.last_name

    };

    console.log(response);

    res.end(JSON.stringify(response));

})


app.listen('8081');

console.log("server is up and running..");

The express module enables you to create a server while the body parser allows you to parse the body in which the user name is sent. Since we need to encode the body, the urlencoded does the job for us.

The post request uses headers to send the data, you may need different types of headers depending upon your requirement(for instance, multipart-form-data to send files and x-www-form-urlencoded to send form data). For more info about headers, click here

req.body refers to the content of the body. If you'd like to fetch specific contents from the body, you may add it at the end of req.body as in the above code where we're fetching first_name using req.body.first_name.

2. To send a request, we first create an interface where we can send the username from.

index.html


<html>

<body>

<form action = "http://localhost:8081/listUsers" method = "POST">

 First Name: <input type = "text" name = "first_name">&nbsp; <br>

 Last Name: <input type = "text" name = "last_name">

 <input type = "submit" value = "Submit">

</form>

</body> 

3. Running the server

Now that we are ready with server and interface, let's run them.

To run the node server, type the following command(presuming you have nodejs installed or you may install it from here)


node server.js

Output

server is up and running..

4. To send a request using the interface, open http:localhost:8081 in your browser and you will be redirected to webpage where you can input username


4. Click on "Submit", which sends a request to the server and you'll get response that returns the username



If you notice the url in the output, you don't find the user name unlike in GET request you'll find the user name in the url itself. The user name in POST request in embedded in the body which is why it doesn't appear in the url. Thus, POST request is considered to be the best practice while sending confidential data.

Here we are representing them in JSON format. Similarly, we may save it to the file or database which I'll demonstrate in the upcoming posts.

Happy coding! ;)