November 2016

This blog post is not about any kind of technology, library or language. It is not about the soft skills either. You see, as a football player (the soccer type), I have been practicing the game for nearly 20 years now. If you are engaged in any kind of sport activity or musical activity, chances are that you have been practicing something (as in repeating a move or a drill over and over).

Musicians play their scales or some piece of music as a warm-up exercise or practice. Athletes prepare their bodies for practice or competition. I can name a few drills that I’ve been doing for 20 years as a football player. Drills that are accepted in this sport as must-do to improve. It is expected for an athlete or a musician to spend time by himself or with a team practicing, without the pressure of the competition.

What about programming?

What drills or exercises programmers do, or must do, in order to become more efficient? Is there any warm-ups that programmers do in order to produce right away?

More mental than physical

It is pretty safe to say that being a programmer relies more on mental skills than physical ones. Solving problems with code. Make sure that we communicate clearly to other developers and clients.

On the physical side on things, make sure that your body posture won’t hurt you. Sit comfortably with your back straight. I could probably imagine one aspect that could be improved physically, how fast we type. Typing without looking the keyboard. You can find places to practice this like typingclub. What about your favourite editor shortcuts? Would it be worth it for programmers to spend some time each day or week learning or practicing these shortcuts?

What about the mental things? Do you have any rituals that make you more focus? Things that make you more efficient in solving problems? I do some meditation personally, and I can feel more focus for some time. But the main thing seems to be the complexity of the problem at hand. If a problem is too simple or way too complicated, I will lose my concentration much more easily than if I have a challenging problem, but not TOO challenging. You know, that sweet spot.

So, yeah, those are a couple of thoughts that I had. I am currently reading Peak from Anders Ericsson and Robert Pool about deliberate practice. I’ll probably write a post about what I read and maybe try to design some things that could make me a better programmer.

In the end, I believe that you need to code to become a better programmer. But repeating the things you already know how to do without trying to make it better or even different won’t get you anywhere. It is clear that the notion of feedback, when one is trying to improve, is always essential.

Let me know what you think, what you do to practice, to improve.

Feel free to share and comment.
Have a nice day!

Read more

As part of my freelancing journey, I have recently being asked to perform a technical test. The content of that test was as follow:

  • Use Javascript on both the front-end and back-end.
  • Users must be notified when another user connects or disconnects
  • The application will send an offer every 15 seconds. This offer will have a random price and can be accepted by the users. After, 30 seconds, that offer expires.
  • Users must be notified when an other user accepts an offer.
  • Users will be authenticated by their IP addresses.
  • Users can see the offers they accepted in the past and the other users connected.
  • Use whatever technology you see fit, no restriction (must be Javascript though)
  • Everything must be in real-time.

Ok, so this was the test. Build a web application that follows those stories. The real-time part is obviously crucial here, and it makes perfect sense. As a potential buyer, I can only buy offers that have not been accepted by another buyer. So, the updates on the offers must be done in real-time. Same thing concerning the connected users. Everybody will have the same information at the same time. One user can’t be shown connected for one user, and disconnected for some.

Now, the previous accepted offers was an interested challenge. Indeed, this feature will change for every single user. Everybody will have accepted different offers. One offer can only be accepted by one user at a time. This part of the application was the most difficult to solve for me. Let me give you a quick overlook of how I did it.

First, what technologies should I use? The real-time concept made me choose I honestly haven’t looked around for other libraries that would allow you to use WebSocket in this way. WebSocket is a web protocol that allows the client and the server to communicate to one another (in real-time). You can find more information about here.

At the time, my knowledge about this library was kind of limited. I knew the basics, but the idea of sockets sending data to only certain sockets was new to me.

If you use the socket.emit() method, the socket will send whatever data it has in its argument to ALL the other sockets, including itself. That is the perfect function for a chat room for example. If a send a message, I want everyone to see it, including myself. Great, but in this case, I’m only looking for that when I display the offers. The server sends the available offers for everybody. What about the other use cases?

Let’s talk about the notifications first. The connection, disconnection of a user, and the user accepting an offer. Here, I want to send the data to everybody except the user that is responsible for that action. In, it means the socket responsible broadcasts the data to the other sockets. Like this:

socket.broadcast.emit('notification', 'User just connected');

Done! I just joined the party, but only the other participants have been notified. Problem solved.

Next, the accepted offers issue. This one was tougher. I couldn’t get my head around this. How do you send the concerned data to the only socket that needs it? I tried to use the method. But that didn’t work. I think this method is only reserved to send data to other sockets. And in this case, I was retrieving the accepted offers from a database, and sending that to the socket. the socket was sending the data to ITSELF. And then, after much research, I found a way to do it.


That’s right. You see, in, you can group sockets in rooms. Think about chat rooms, it works the same! When I join a room in a chat application, I won’t receive the messages from other rooms I’m not a part of. Well, that’s exactly what I needed to do here! Create a room for each user, and broadcast the data of their offers to their room of one. I needed to make sure that each room would have a unique name, so different users would not have colliding room names (therefore wrong data concerning offers) by accident. Well, remember the list of user stories. Users are recognized by IP addresses, so:

//get IP address of the socket at the connection
const userIP = socket.handshake.address;
//create unique room

Then, in order to send data to this particular socket, I used:;

And voila! Use the io global to get all sockets and filter the existing rooms. I tell the application to only send the data to the sockets in that particular room. And because I used the IP addresses, there is only one member in each room, and no risk of sending data to the wrong person.

If you want to see the application live, it is hosted on Heroku here.

As usual, I’m sure there is a better way to do this, more elegant way. But, the first step is to make it work. It does! I would probably need more intel about the WebSocket protocol and the library. But it was a really fun little project to work on.

As always, thank you for your time, and feel free to share and comment!

Have a nice day!

Read more

I love Open Source. I committed myself to learn with Open Source when I started this journey as a developer. I benefited immensely thanks to the community. The tools, the courses, the people… But, one thing I have struggled with is, how do I give back? How can I help Open Source like it has helped me?


The first steps to contribution to an Open Source project are complicated. You may have read about some stories already. Mine is not different. As of today, my contributions include some translation for the FreeCodeCamp repository and some CSS syntax stuff for a project that I forgot… I just replace some ‘-‘ by ‘_’ . Nothing really big, but you have to start somewhere.


When you are looking to contribute for the first time, I believe the most important thing is the community you will be part of. Are they helpful? Do they welcome new contributors? Do they help you overcome difficulties or just dissuade you? These are very important questions because you will most likely participate in a project with at least thousands of lines of code. It can be overwhelming. If the people maintaining the project have no interest in helping you making the project grow, well, maybe you should look for a better place, especially if you are a beginner.


The second thing that you should consider is, do you actually care about the project you want to contribute to? I remember the first contribution I made, the CSS thing. Well, I can’t even remember the name… I think I found it on up-for-grabs and just found a easy enough  issue. People were nice, helpful and all but… I just didn’t really care about the repository. I just wanted to contribute. So, if you are a beginner in the world of Open Source and you want to contribute, find a project that you use all the time, or something that really excites you and emerges yourself in it.
Finally, and I often come back to this, you will have to overcome the imposter syndrome. Those projects seems like well-oiled machines. You’ll be scared to fuck things up. The thing is, Open Source NEEDS you, it NEEDS us. Developers who care about those things. Open Source is amazing, and we can all be a part of that. You don’t have to spend 20 hours a week on GitHub, solving issues. It’s all up to you. Whatever time you want to invest.


Be patient, you will find your place, your community. And you will make software better.


As for me, I decided to concentrate my effort on Calypso. The Javascript and API powered I chose this project because it has everything I want. As a freelancer, making website with WordPress will become a big occupation of mine. As a NodeJS and React fan, Calypso is a project I would love to learn with and contribute to. You can find the repository here


I’m actually off to spend some time in the code to try solving an issue. It’s difficult, it will take time for me to figure out. But that’s the best part.


Have fun.
As always, feel free to share and comment.
Have a nice day.
Read more

Join me during my amazing adventures: Damien tries to become a freelancer !

I recently started taking freelancing seriously. A lot more seriously than I did in the past. I’m at a point where I’m considering becoming a freelancer full-time, as my primary (only) occupation. So, I decided to write about it. It will probably help me getting through the struggles I face more easily. Or maybe some of you considering making a move into the freelancer world will find some comfort in my words.


Anyway, a few things triggered this attraction to the freelancing world:
– the freedom the freelancer has (Yay!)
– the current difficulty I have to find a job in my area (not cool)
– my very own brother asked me to build an e-commerce website for him (that’s nice)


With that in mind, I talked myself into becoming a freelancer. But, because I’m also the type of person that can spend months researching and planning without doing anything, I decided to just go for it. I believe this is the best plan, even if I know I will fuck things up (I even already did… sort of).


So, one thing you might hear about freelancing is the importance of networks. Well, my brother is giving me my first gig after all. But, to be honest, my network is limited to my family. I don’t have any head start here. This means, I have to spend some time on online job boards to look for gigs.


I started with Upwork, and i saw a blog post on Medium. You may have read it. It really freaked me out. So, I crossed Upward for good. I am currently on PeoplePerHour, and it’s going good so far.


Okay, I know you are all waiting for the story where I fuck things up. Here it is. The very first job that I find, and so far the only one, was about adding some functionality on the EspoCRM. I never heard of it before, but the job talked about javascript and json. I thought, well this is for me. Oh boy was I wrong. The man was really nice, patient, took the time to explain to me what I needed to do.


I understood the requirements, the thing is, I never touched such a platform before. Now, that might not be so bad. So, I spent a few hours trying to wrap my head around a plausible solution. Nothing, no-thing. So, I tell the client that the job is a lot more difficult than I thought (urgh…). So, we talk to each other on teamviewer, explain it again, very patiently. And he even gives me other possible solutions that would work for me (!!!) . One of those seems doable, so he gives me two hours to tell him if I can do it or not.


I got further than the last try… But, I couldn’t get the functionality to work properly… What a awful feeling that somebody trust you to solve a problem, and you just can’t do it. So, I just told him he should probably find a freelancer more qualified than me. Yeah, not good..
The feeling is pretty terrible … But, I can get a few lessons from that adventure.


– Be honest. If I realised I couldn’t do it. I won’t lie to the client. Own it. Apologise for wasting their time and move on. It may happen again, but there is no excuse for lying about the abilities. I thought I could, I was wrong. I’m really sorry. Moving on to my next mistake.


– Be careful about what you are working with. I’m sure this will not be the last time I will deal with a platform, library or software I’m not used to, but I have to be realistic about what I can achieve with my current knowledge. I like the lesson in humility though. Be careful not confuse this with a feeling of worthlessness. It’s not true, and it really doesn’t help you. Dismiss this feeling.


– Don’t feel bad for too long about this. The client may yell at you, but upset, even give you a bad recommendation. Unfortunately, I think those things are part of the journey, at the beginning.


This is the end of my first chapter. I will keep learning about this freelancing stuff. I will keep learning about programming. I will learn how to get the right clients, clients whose problems I can solve with my skill set.


As always, feel free to share and comment.
Have a nice day.
Read more

For a very long time, I’ve always admired people who found their calling. People that just says ‘Well, I just do what I always wanted to do.’ . I was jealous of that. Knowing what is right for you from the start. The headaches you must save yourself if you are that lucky person. So, because I didn’t have that chance, I just though something was wrong with me.

Right? ​NO!

​Nothing is wrong with me. There is simple explanation to this: Passions are not born, they are cultivated. Nobody wakes up one morning with the perfect career choice in their mind. The path that will be just right for them. Impossible. Some may find the right career path on their first time. But the environment around us defines a lot of things about what we do.
It is the good old nature vs nurture debate. Our genes against what surrounds us.


​​The​ assumption that I had before I started reading literature about the subject was: we must have control about our environment (nurture) and close to no control on our genes (nature). Well, that’s actually the opposite. We do not fully control our environment. I am an avid reader, I love it. Why? My mom used to read a lot too. The people, the culture that surrounds us are very likely to shape who we are as human beings. It makes sense. We, as children, must learn from people we interact with. At first, our parents. Then, our teachers and classmates. We are a product of the people we spend time with.
So, when you start playing the piano at 5, become a very good player at 13, and gives breathtaking concerts at 18, what’s going on? We must look at the environment. Are mom and dad musicians? Most likely. Mozart father was a composer that forced him to practice hours on end.

B-Picking the passion

When I look back at my life, nothing tells me that my environment pushed my towards programming. So, how do I explain the fact that I sticked with it?
In the George Leonard’s book Mastery, the author takes about three kinds of people in their path to mastery. The Dabbler, the Obsessive and the Hacker.

The Dabbler loves new things. He is very excited about trying a new sport, a new job, a new career. Getting the fancy stuff to get started. The first lessons are amazing, this IS the right thing for him. Then, he hits a plateau, the excitement fades, and disappear. The Dabbler looks for something new to get excited about.

The Obsessive is different in the way he sees the first plateau or falloff he hits. He doesn’t accept it, he can’t accept it. So he works harder, he must get everything right, right from the start. He stays longer at the office, ignore advice and just keep pushing. He manages to keep the fire alive in short spurts, pushing just one more time. Until he just quits.

Finally, the Hacker is very different. He is perfectly fine is the plateau that he hits. The Hacker gets by, doesn’t have a strong desire to improve. He gets the hang of one thing, and just think that’s all he needs. Every break he can get, he takes. He is fine with other Hackers around him. But if the people around start improving, ouch!

I am a Dabbler. i love trying new things. I tried a LOT of things. I buy the instrument, the books, sign up for that app. Yeah, this is my thing now. I envision myself being an expert at whatever new thing I picked up. I improve! Oh my God, this is it! I found my calling, finally!
Then, the plateau. The initial excitement is no longer here. And I just find something new to do.

This description of the Dabbler hits home for me. And I realised it was not sustainable. So I read more books about talent, finding your calling, having the right path, happiness. One day, I started to teach myself how to code. And I sticked with it. Why?

C-Having something to show

My first attempt at learning how to code was with C. I read that many languages derived from C, it is like the latin of programming languages. I thought, well I must start here. It will give me all the tools necessary to become awesome. So, I picked up Learning C for Dummies. Want to take a wild guess at what happened?

Yeah, I quit after a few weeks. I read about compilation, about the loops, the if-else…
I saw the stuff printed in my terminal… So boring…
Then, I discovered Treehouse and I signed up for the 14 days free trial. And I got into it. A year later, I’m still into it. Why? Because I built something right away.
You see, now, a lot of courses online make you write code right away. And this is so important. You are engaged, you are not drowning in the technical terms. You just do something of value, you feel useful. I made an HTML page! Now that I look back at it, it was nothing. A few tags, a header… But it was all me! I made it work!

Then, we added CSS, a bit of Javascript. An image here. And soon, my very own website was online. I still remember the feeling of wonder and amazement I had when it went live. I couldn’t believe I did this. I couldn’t believe of the road I had travelled. Sure, it was just a website, but it was mine. It wasn’t much, but that little thing was my baby.

This is what you must look for when finding a passion. Look for a teacher, or a course that will engage you in the task. Make you feel useful. Not just bore you with endless theories.

Make sure you build something, even the smallest thing possible!

As always, feel free to share and ask questions!
Have a nice day!

Read more


In this article, we will make a very simple API (Application Programming Interface) with Express and Mongoose. We will create a program that will talk to a database. What we do with the database will be defined by the routes and the method we enter. An API is only on the back-end side of the application. We will not take care of connecting this API to the front-end (but you could do it without a problem).

To achieve this, we will use Express, Mongoose and Postman. Mongoose is an ODM (Object Document Mapper).It makes it easier to connect and interact with a mongodb database.
Postman is a tool that allows you to test and run your APIs. It’s a really great tool that can be found here.

A- Database and model

First let’s start by installing the packages we’ll need to interact with the database. In order to install MongoDB and use it on the command line, you can follow the tutorials here.

When this is done, create a new directory and add two files: model.js and index.js.
First things first, let’s install our dependencies, with this command:

npm install express mongoose body-parser

In model.js, we will create a Schema. A Schema represents the data you want to store in your database. A Schema takes a JSON Object. Like this:

const mongoose = require('mongoose');
let Schema = mongoose.Schema;

let AlbumSchema = new Schema({
	title: String,
	year_release: Number,
	artist: String,
	genre: String

let Album = mongoose.model('Album', AlbumSchema);

module.exports = Album;

We require the mongoose package. Then, I create a variable Schema that will allow me to instantiate a new Schema. this application will store albums, so I give my Schema the name AlbumSchema. As you can see, my schema takes a JSON object with 4 keys. Each key has a value that corresponds to its data types. You can find more information on the mongoose data types here. For this example, three keys are String, one is Number.
The mongoose Schema needs to be stored into a model. We do this by calling the model() method. It takes two arguments, the first is a string and defines the name of your model. The second argument is the schema concerned. Finally, I export this model.
Great, now let’s move on to our routes

B- Database Connection And Routes

Let’s open our index.js and require our dependencies:

const mongoose = require('mongoose');
const Album = require('./model');
const express = require('express');
const jsonParser = require('body-parser').json;

const app = express();

app.listen(3000, () => {
	console.log('Listening on port 3000');

Nothing crazy here. I require mongoose, my Album model, express and body-parser. We use the body-parser to transform our requests bodies to JSON. It makes it a lot easier to work with data. Next, I instantiate a new Express application and use our parser in the middleware. Finally, I tell the app to listen to the port 3000.

Next, let’s connect to our database. We are going to use the local machine. Here is what it will look like. Add this to your index.js

//connect to db
const db = mongoose.connection;

db.on('open', () => {
	console.log('You are new connected to the database');

db.on('error', (err) => {
	console.log('An error occured!', err);

The mongoose.connect() takes the url of the database. On your local machine, it will have this form mongodb://localhost/ . Then, you enter the name of your database. Here, I chose mongoose-test.
To be able to interact with your database, you need to start the mongo deamon. It is included with the MongoDB installation that you did earlier. All you need to do is open a new terminal window and enter the command:


Now, if you start your app with node index.js(in a different terminal window). You will see:

Listening on port 3000
You are new connected to the database

Let’s create our routes!
Here is what I chose to do: Two GET routes, one to get all the albums of the database and an other one to get an album based on its id. There is one POST route to create a new album and a DELETE route to delete an album based on its id. You can of course create more if you wish. Here is what it looks like for me.


// GET all albums in database
app.get('/', (req, res) => {
	Album.find({}, (err, albums) => {
		if(err) return next(err);

//GET album by id
app.get('/album/:id', (req, res, next) => {
	let id =;
	Album.findById(id, (err, album) => {
		if(err) return next(err);
			res.json({message: 'No album with this ID in the DB!'});

//POST new album'/album', (req, res) => {
	let album = new Album({
		title: req.body.title,
		artist: req.body.artist,
		year_release: req.body.year_release,
		genre: req.body.genre
	res.end('The album ' + req.body.title + ' has been saved');

//DELETE album by id
app.delete('/album/:id', (req, res, next) => {
	let id =;
	Album.findById(id, (err, album) => {
		if(err) return next(err);
			res.end('No Album with this ID!');
		res.end('Album has been deleted');

As you can see, we use the findById method on the model to find a particular document. The id is automatically added by mongoose, you do not have to take care of that. To find all documents, we give the find method an empty object. To get the id from the url, we use the express req.params property.
Let’s see this in action! Launch Postman.
At the top, you can find the url bar and the method. In our case, the URL will be http://localhost:3000/ .
You can start by adding an album of your choice by choosing the POST method and the url http://localhost:3000/album. Then, select Body in the sub-menu. Pick raw in the radio boxes and choose application/json in the dropdown. Now, enter a JSON object with the properties specified in our model (year, title, artist, genre) and press Send. Our API will process and add this document to the database.
If you choose GET method and the ‘/’ path, you will be able to see all the albums you add.
Note:the id you specify to see a certain album or delete must be the one added by the MongoDB database. It’s the value you see in the key _id. It has this form :

"_id": "5822fd543990280b9cfded04"

Well, there you have it! A very simple API that should get you started with mongoose.
Feel free to ask questions and tell me what you think.
Have a nice day!

Read more


In the world we live in today, a person looking for a job is no longer restricted by the location he lives in. The state of communications makes it a lot easier to work from home, for a company on the other side of the planet. Entrepreneurship allows individuals to look for work all by themselves, without having to rely on a company to do it for them. Many people choose this way of making money, taking care of every step along the way. It is an ode to freedom, having the responsibility to market its skills, and choose who you want to work with.
I currently am looking for a job. So, because the prospect of freedom is appealing, I decided to look a bit deeper at the possibilities in front of me. In this blog post, I will list the things I found in my researches.

The employee

Let’s start by the most common, being an employee. Surely the safest way to make money each month. As long as I am employed, I get my check at the end of the month. Depending of your country, you will get different advantages with it. We can distinguish, in my opinion, two sorts of employees. The first one will be the ‘Go to the office everyday’, probably the only one our parents are aware of. But, in the industry of technology, a second kind of employee was born: the work-from-home employee. The remote position. The freedom of working from home, while having a safe check at the end of each month. Pretty appealing.

My take: Jobs involving Node.JS around my area are very rare. As of now, I am more looking for remote positions. Even if I am not extremely please with it, I might have to consider moving closer to a larger city where I will have more options.

The freelancer

The second option I considered was to become a freelancer. The freelancer is responsible for finding is own clients. He has to market himself, convince potential clients, do the work. This option probably embodies the idea of freedom the most. No boss, no colleagues. You choose the work you want to do (assuming you have enough work to be picky). It is also less safe than the employee. Since you are in charge of finding your own work, your income is not always guaranteed. Especially when you are starting out. How can you convince people that you will do a good job, if you’ve never done a job before?

My take: I am currently starting to freelance. It will allow me to have more experience and make some money on the side while I keep looking for a job. Of course, I don’t close the door to becoming a full-time freelancer, but it simply isn’t a priority right now.

The entrepreneur

I kept the most difficult option for last. The entrepreneur. The ‘let’s create my own startup king-of-guy’. I would be lying if I said I never entertained the idea. The entrepreneur is for sure the path that will be the most rewarding in terms of money and recognition. But it most certainly is a complicated route to follow. Creating a product, marketing, selling… It looks really attractive, and some of you are probably ready for this, but not me, not now.

My take: Preparation is key. I simply didn’t prepare for this possibility yet. Maybe in a few years when I am more certain about my career.


For me, the plan is as follows: Find a job, become an employee. It seems like the logical first step in a career. Like I said, I am currently looking for remote position while considering a possible relocation in the near future. On the side, I am starting to do some freelancing, for the experience and of course a bit of money. It will also force me to learn how to market myself to potential employers.

As always, let me know what you think.
Feel free to share and comment!
Have a nice day!

Read more


Node.Js offers us only a few modules to get started, but they are extremely useful. When you build a platform like Node.Js, your goal is to have components that make it easy to build on top. In my learning journey in Node.Js, I like to study a little bit deeper the source code of those modules. So, for the purpose of this article, I chose to look at the querystring module. You can find the documentation here and the source code here.

The Query String module

The query string module is a small one. 413 lines (with all the comments). If you look at the docs, there are only 4 main functions. escape, unescape, stringify and parse.
As its name indicates, this module works on the query part of an URL. Let’s use the URL module to get the details of an URL. Let’s create a file:

const url = require('url');

let urlStr = '';

In this example, we want the details of the google’s homepage URL. To achieve this, we use the url.parse() function.
When you run this file, here is what your console will print:

Url {
  protocol: 'https:',
  slashes: true,
  auth: null,
  host: '',
  port: null,
  hostname: '',
  hash: null,
  search: '?gfe_rd=cr&ei=CK0ZWOmGJoqg8wfUjIGYCw',
  query: 'gfe_rd=cr&ei=CK0ZWOmGJoqg8wfUjIGYCw',
  pathname: '/',
  path: '/?gfe_rd=cr&ei=CK0ZWOmGJoqg8wfUjIGYCw',
  href: '' }

Here are the details of this URL. We get a URL object back. In this object, you can see a query key. This is what the query string module works on. It is everything after the protocol, host and pathname.
Great, now we know the scope of our module. Let’s see the functions it offers us.

A- parse()

We will start we the parse function.It takes one mandatory parameter, a string. If we keep the previous example with the google’s homepage, let’s parse the query of the URL like this:

const qs = require('querystring');
let urlQuery = 'gfe_rd=cr&ei=CK0ZWOmGJoqg8wfUjIGYCw';

After running this, the console returns:

{ gfe_rd: 'cr', ei: 'CK0ZWOmGJoqg8wfUjIGYCw' }

We can see a pattern here. The ‘&’ sign acts as a separator between key:value pairs, and the ‘=’ acts as the separator between each key and value. This two signs are the defaults signs. You can change them. The parse function takes 3 optional parameters. The first one defaults to ‘&’, in order to delimit key and value pairs in the query string. The second one defaults to ‘=’, in order to delimit keys and values. Let’s try to change them in our query string and our function:

const qs = require('querystring');
let urlQuery = 'gfe_rd:cr!ei:CK0ZWOmGJoqg8wfUjIGYCw';
console.log(qs.parse(urlQuery, '!', ':'));

We replaced the ‘&’ by ‘!’ and the ‘=’ by ‘:’. If we run this, we will get the exact same result than before.
Note: If you do not specify the right separators in your functions, you will just get your query string as an empty key. Most URLs use the ‘&’ and ‘=’ as separators, this is why they are the defaults.

The third optional parameters takes a object. This object has two keys by default. The first one (decodeURIComponent) takes the function querystring.unescape() as a value. We will see this function later in this article. this is the place where you specify how to deal with percent encoded characters (such as %20 for spaces). The second key is maxKeys, and it defaults to 1000. It specifies the number of keys to parse. It allows you to have more control over really long URLs. Give it 0 if you wish to remove any kind of limitations.

Let’s move on to stringify.

B- stringify

The stringify function is the opposite of parse. It takes one mandatory parameter, an object. It transforms it into a query string. Like this:

const qs = require('querystring');
let queryObj = { gfe_rd: 'cr', ei: 'CK0ZWOmGJoqg8wfUjIGYCw' };

We take the object the parse function returned last section and call it as the stringify argument.
In our console, here is what we get back:


We find the same query string than before. However, just like the parse function, the stringify function takes 3 optional parameters. The first two are the same, they define the separators. Let’s change them:

const qs = require('querystring');
let queryObj = { gfe_rd: 'cr', ei: 'CK0ZWOmGJoqg8wfUjIGYCw' };
console.log(qs.stringify(queryObj, '!', ':'));

We change the parameters to equal ‘!’ and ‘:’. Here is the result:


We get back the query string with the separators we specified.
The third optional parameter is different than the one in parse. It only takes the encodeURIComponent key. It takes the default function, querystring.escape().
Let’s take a look at this escape function now.

C- escape

The escape function is fairly straightforward. It takes one parameter, a string. URLs have a specification that makes certain characters unsafe. The escape function makes sure that the query strings are escaped with percent-encoding. Here is what it gives us with a random query string:

const qs = require('querystring');
let queryToEscape = 'this could be&areally cool!String=to,escape?Is it_éven$~possißle??';

Here is how this query looks like when it’s escaped:


The ‘&’, ‘=’, ‘?’, ‘é’, ‘ß’, ‘,’ , ‘$’ and spaces are all percent-encoded now. As we saw earlier, this function is used by stringify. You will probably rarely use it yourself.
Let’s see the last function, unescape.

D- unescape

As we might have guessed, the unescape function does the opposite of escape. It decodes percent-encoded character into a normal string. Like this:

const qs = require('querystring');
let queryToDecode = 'this%20could%20be%26areally%20cool!String%3Dto%2Cescape%3FIs%20it_%C3%A9ven%24~possi%C3%9Fle%3F%3F';

We use the result we got from the escape example and decode it. Without a surprise, we get the original string with the spaces and all the special characters back. As you saw, this function is used in the parse function. Just like the escape, this function will probably rarely be used directly. Nice little thing to note, this function uses the built-in Javascript function decodeURIComponent. You can find more information about it here.


I wrote this article as part of a learning process. I believe it is very good to dig into the source code of a project to learn more about it. The Query String module gave me a relatively simple starting point. It is very short and pretty easy to grasp. I encourage you to read the module’s code on GitHub and see how they implemented those functions. I didn’t understand everything, but it’s always a good idea to expose yourself to other people’s code. I did learn a few things during the process, and will most certainly try it again sometime soon.

As always, feel free to share and comment.
Have a nice day!

Read more