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 socket.io. 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 socket.io 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 socket.io, 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 socket.broadcast.to(socketID) 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.

Rooms

That’s right. You see, in socket.io, 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
socket.join(userIP);

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

io.sockets.in(userIP).emit(data);

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 socket.io 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 WordPress.com. 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.

A-Control

​​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

Introduction

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.use(jsonParser());

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
mongoose.connect('mongodb://localhost/mongoose-test');
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:

mongod

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

Awesome!
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.

index.js

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

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

//POST new album
app.post('/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
	});
	album.save();
	res.end('The album ' + req.body.title + ' has been saved');
});

//DELETE album by id
app.delete('/album/:id', (req, res, next) => {
	let id = req.params.id;
	Album.findById(id, (err, album) => {
		if(err) return next(err);
		if(!album){
			res.end('No Album with this ID!');
		}
		album.remove();
		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

Introduction

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.

Conclusion

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

Introduction

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 = 'https://www.google.fr/?gfe_rd=cr&ei=CK0ZWOmGJoqg8wfUjIGYCw';
console.log(url.parse(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: 'www.google.fr',
  port: null,
  hostname: 'www.google.fr',
  hash: null,
  search: '?gfe_rd=cr&ei=CK0ZWOmGJoqg8wfUjIGYCw',
  query: 'gfe_rd=cr&ei=CK0ZWOmGJoqg8wfUjIGYCw',
  pathname: '/',
  path: '/?gfe_rd=cr&ei=CK0ZWOmGJoqg8wfUjIGYCw',
  href: 'https://www.google.fr/?gfe_rd=cr&ei=CK0ZWOmGJoqg8wfUjIGYCw' }

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';
console.log(qs.parse(urlQuery));

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' };
console.log(qs.stringify(queryObj));

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:

gfe_rd=cr&ei=CK0ZWOmGJoqg8wfUjIGYCw

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:

gfe_rd:cr!ei:CK0ZWOmGJoqg8wfUjIGYCw

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??';
console.log(qs.escape(queryToEscape));

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

this%20could%20be%26areally%20cool!String%3Dto%2Cescape%3FIs%20it_%C3%A9ven%24~possi%C3%9Fle%3F%3F

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';
console.log(qs.unescape(queryToDecode));

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.

Conclusion

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

What is Express?

Express is a web framework. It provides a very minimalist structure to build web applications. Express shares the same spirit as NodeJs. Express is unopinionated, fast and small. This framework doesn’t force you down a certain path. It only gives you a solid foundation to build upon. This is why Express is a very popular tool in the community. In this article, I will show you a extremely simple Express application. Nothing crazy. It will contain a single file that will help you have something up and running in no time. Then, I will show you the Express generator that creates a full skeleton of a Express application. Let’s get started.

Install and Run

Let’s create a directory called simple-express-app. In this directory, create a single file called index.js.
The first thing we want to do is install Express globally. To do so, open your terminal and enter this command:

npm install -g express

Note: you may have to use sudo for this command.

Great, now open your index.js:

Explanation: we import express in the first line. Then, we instantiate a new Express application and store it in the variable app. This new Express instance allow us to use a lot of amazing methods on it. Here, because this is a simple example. We use the get method. This handles the HTTP GET requests to the specified path.
On line 4, we tell Express how to handle the GET requests made for our index page (‘/’). The callback function takes three parameters, a request, a response and next. You will often times see this abbreviated as req, res, next. We can access the request object thanks to req and control the way our response will be with the res object. The next function tells Express to call the next matching route. We will see it in use a bit later when we will use middlewares.
So, our index page is going to end the response by sending the string ‘Hey Home’.
On line 9, we handle the GET request at the /about path. This time, we decide to send a JSON response. Then, we need to tell our application which port it should listen to.
So if we run this application with:

node index.js

and then visit our http://localhost:3000/ , we see => ‘Hey Home’. If we go to http://localhost:3000/about , we get => {message: ‘About Page’} . Awesome!

Now, let’s go a bit deeper and use something called a middleware. As its name indicates, a middleware is something that is used in the middle. Let me show you a quick example by changing our index.js file like this:

We use middlewares in Express with the use method. Every time our application receives a request, but before we give control back to our other routes, we will run the middleware at line 4 (in the middle remember?). This way, we have a lot more control over our application and it prevents duplicate code. In this example, we log a string with the URL, the hostname and the method. Then, we tell our response object to display HTML in the browser when the status code is 200 (meaning everything is OK). I do not have to tell each route how to display its content, nor do I have to write the console.log statement everytime. Let’s run this file now.

If you visit the homepage or the about page, you will see the corresponding HTML and the log in the console. But, if you go to a path that we do not handle, /contact for example, you will still have the log in you console. Remember, the middleware is called before the response is emitted. Then, we call next(). Earlier, I said that next passes control to the next matching route. So, if I visit /about, when next() is called in our middleware, we run app.get(‘/about’ …. But, if I visit a page that we do not handle, our server will just hang … We could add a little piece of code after our routes like this one :

app.use('*', (req, res, next) => {
    res.end('Page not found');
});

If our server can’t find a matching route, we will just print out ‘Page not found’. Our first middleware will log our string and pass control to this new middleware if no path matches. The ‘*’ is a shortcut for all the routes.
Note: Make sure to add this middleware after all the other routes. Otherwise, you will always see ‘Page not found’.

Ok, we have a very simple Express application that allows you to understand a little bit what Express is about. We only scratch the surface here and it would be impossible to explore every Express possibility in one blog post. In the last section, we will see how the Express executable work.

Express Generator

The Express executable does a lot of good things for you. It creates a skeleton for your app and allows you to choose a template engine. Express provides support for a variety of different template engines. Those engines let’s you pass data to your view. It’s pretty much HTML on steroids. You can pass markup, data, add some logic … But, this is outside the scope of this article. You can have more info about the executable by tying the command:

 express --help

  Usage: express [options] [dir]

  Options:

    -h, --help          output usage information
    -V, --version       output the version number
    -e, --ejs           add ejs engine support (defaults to jade)
        --hbs           add handlebars engine support
    -H, --hogan         add hogan.js engine support
    -c, --css   add stylesheet  support (less|stylus|compass|sass) (defaults to plain css)
        --git           add .gitignore
    -f, --force         force on non-empty directory

In addition, you could specify a CSS preprocessor using the –css option, or enable session middleware with –sessions.
Ok, let’s just see what this thing does. I’ll just create a application called myApp and use the hogan template engine.

express -H myApp

And here is the result:

express -H myApp

   create : myApp
   create : myApp/package.json
   create : myApp/app.js
   create : myApp/public
   create : myApp/public/javascripts
   create : myApp/public/images
   create : myApp/public/stylesheets
   create : myApp/public/stylesheets/style.css
   create : myApp/routes
   create : myApp/routes/index.js
   create : myApp/routes/users.js
   create : myApp/views
   create : myApp/views/index.hjs
   create : myApp/views/error.hjs
   create : myApp/bin
   create : myApp/bin/www

   install dependencies:
     $ cd myApp && npm install

   run the app:
     $ DEBUG=myApp:* npm start

As you can now see, you have a shiny new directory with a nice application skeleton. You have to install the few dependencies that were generated and you are good to go! We won’t cover everything, but let’s just take a look at our entry point: app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;

Alright, let’s break this down a bit. The first lines import all the dependencies. Then, we require the files responsible for our routes. you can use a Router with Express, to make it simpler to handle your routes. You can get more information here. Then, with the two app.set lines. We tell our application where our views are and which template engine we use (I chose Hogan for this). The next block serves as a configuration for our app. The bodyParser will allow your application to parse the request bodies for example. The logger will log friendly output in your console. The express.static middleware tells Express where to find your static files. Here, we will look in the public directory.
You can run this application with

npm start

and visit localhost:3000 .

Congratulations, you have now a solid skeleton for your future web applications! I highly encourage you to play around with the Express generator and see what each part does. Remember that this framework really doesn’t force you on any path. The generator only gives you some tools to improve your development process and a Router. You still have complete control over the tools you want to implement and the path you want to take.
Express is a really great tool to learn and explore all the possibilities of web development.

Have fun.
As always, feel free to share and ask questions.
Have a great day!

Read more

Introduction

In this article, I will give you a quick overview of Webpack. As you may know, JavaScript is everywhere, so the number of tools created by the community increases as a consequence. It is most certainly the sign of a very healthy environment. We, as developers, are trying to improve our workflow, make better products, and make them available for a wide variety of users. But, when you are in a learning process, it is extremely easy to become overwhelmed by all the possible things you can learn. You may have read a few articles about ‘JavaScript Fatigue’ like this one or this one.

As I keep trying to improve my skills as a developer, I can start to recognize a pattern in the most popular tools, libraries and frameworks. React is becoming ( or has become already? ) a very popular library. But, with React, you may have heard about a tool called Webpack. Webpack is a very powerful tool. I’ll try my best to make it as understandable as possible. Here is what I will cover in the article:

  • What problems do Webpack solves?
  • A quick start with Webpack
  • Adding the webpack.config.js
  • Webpack with React

Let’s jump right in!

1) What problems do Webpack solves?

If you are familiar with JavaScript, you may already know about modules. Modules allow us to separate our code into small files to make it more readable and modular. Then, we can export and import those modules in other files when we need them. It makes our code DRY(don’t repeat yourself), easier to test, debug… Well, it’s just awesome.
Node.js use a module conventions called CommonJS. You can find more information about it here. Basically, you use require() to import modules from other file, and the module.exports object to export them. Something like this:

hello.js

const hello = function(){
    console.log('Hello World');
}
module.exports = hello;

sayHello.js

const helloFunc = require('./hello.js');
helloFunc(); // Hello World

Now, all of this works great in the Node.js environment. The CommonJS modules are the default mechanism and ES6 syntax is supported, because the engine that runs Node.js keeps up with the JavaScript standards. The problem comes with the browser space. The browsers have a very fragmented way to support modules. Some browsers have a environment that supports CommonJS modules, just like Node.js. But other browsers might support a environment based on AMD (Asynchronous Module Definition) loader (RequireJS for example). And some browsers don’t even have a module system at all, meaning that they use globals to access other modules.

So, how do I make sure that the I can use the modules I write in every browser? Enter Webpack. Webpack is a module bundler. It allows us to write modules just like you would do it in Node.js. Webpack will then scan your require() statements and resolves the references modules into a bundle. Webpack goes through a compilation step and creates a bundle(single file) that you can easily include in a web page. If this sounds a little complicated, don’t worry, I’ll show you some examples!

2)A quick start with Webpack

Let’s see a real example of Webpack in action.
First, you need to install Webpack. Go to your terminal and type:

npm install -g webpack

Note: you may have to sudo for this.
Now, let’s create three files: main.js, sayHello.js and index.html.

In main.js, let’s write a simple module:

module.exports.sayHello = function(name){
	return 'Hello ' + name ;
};

Nothing crazy, we populate the module.exports object with a sayHello method. this method is a anonymous function that takes a name parameter a return string with that name. As you can see, we are using the CommonJS module pattern with module.exports (just like in Node.js).

Next, let’s write our browser code in sayHello.js :

var sayHello = require('./main.js').sayHello;
var hello = sayHello('My Dear Browser');
var body = document.getElementsByTagName('body')[0];
body.innerHTML = hello;

Here, we import the module with require(). Then, we use vanilla JavaScript to call the function, get the body element, and insert our string inside of it.

Now, here comes the magical step. In your terminal, run this command:

webpack sayHello.js bundle.js

We tell webpack to compile the sayHello module and bundle all the required dependencies inside a single file called bundle.js. Now, we can use this in the browser.
To use it in our index.html, add a script with the src attribute equal to bundle.js.

That is all we need to run our code. Open your index.html file in your browser and tadaaaa !
Cool, right? But this is just the tip of the iceberg. Webpack has many other advantages:
-Webpack can generate bundles for different modules
-We can use third-party loaders and plugins for almost everything: ES2015, CoffeeScript, TypeScript …
-Webpack can pre-process our stylesheets, images, fonts …
-Can be runned from task managers such a grunt or gulp
-Webpack has a watch mode, meaning we don’t have to run the command from the terminal after each change.
And many many more…

3) Adding the webpack.config.js file

To go a little bit deeper with Webpack, we will use a configuration file called webpack.config.js. This file exports a configuration object that will be read by Webpack when we invoke it without any arguments in the terminal.
Let’s say that, in our previous example, we wanted to use ES2015 (ES6) syntax. Well, we can configure this in our webpack.config.js file. But first, for clarity, let’s move our main.js and sayHello.js files into a src/ folder. Let’s change those files with some ES6 syntax.

main.js

module.exports.sayHello = (name)=>{
	return 'Hello ' + name;
};

We use the arrow function syntax here.

sayHello.js

const sayHello = require('./main.js').sayHello;

const hello = sayHello('My Dear Browser');
let body = document.getElementsByTagName('body')[0];
body.innerHTML = hello;

Here, we use const and let keywords.
Let’s create webpack.config.js in the root of our directory (not in the src folder!) and type:

const path = require('path');

module.exports = {
	entry: path.join(__dirname, 'src', 'sayHello.js'),
	output: {
		path: path.join(__dirname, 'dist'),
		filename: 'bundle.js'
	},
	module: {
		loaders: [
			{
				loader: 'babel-loader',
				query: {
					presets: ['es2015']
				}
			}
		]
	}
};

Ok, let me explain. The entry defines the entry point, and the output defines the destination of our bundle file. In the previous examples, those were the first and second arguments we gave after the webpack command in our terminal. Next, in the module object, we define the loaders. We know that we need to compile our ES2015 (or ES6) syntax back to ES5 where every single browser can read it. So we use Babel for this. The loaders is an array of objects that defines each loader. For this example, we only use one, but we can use a lot more.

Before running this: we need to install Babel and the ES2015 preset:

npm install babel-core babel-loader babel-preset-es2015

Great, last thing, don’t forget to change the path of your bundle in your index.html as dist/bundle.js. As you can see in the output of our file, the destination is in the dist folder now. It is considered good practice to keep your source files and your bundles separated. Now, you can simply run:

webpack

And, now, you have a new folder dist that contains our bundle. And every browser can understand our syntax thanks to Webpack and Babel. Yay!

Note, to launch the watch mode, you can run: webpack -w

4) Webpack with React

A lot of people are drawn to Webpack because of React (at least I was). So, in this section, we will talk about configuring your Webpack to work with React. Compared to the last section, there is not that much configuration required. What is the difference between the code we wrote before and React? Well, you most likely write you code in JSX, the JavaScript superset that makes React easier to work with. So, we need to tell our Babel loader to compile JSX into ES5 code. We just need to add ‘react’ in the presets array like this:

loaders:[
    {
        loader: 'babel-loader',
        query: {
            presets: ['es2015', 'react']
       }
    }
]

Let’s create a new folder. Create two files, webpack.config.js and index.html. Then, create a src folder. Inside this one, create two files, main.js and greetings.js. Our Webpack configuration file will look like this.

webpack.config.js

const path = require('path');

module.exports = {
	entry: path.join(__dirname, 'src', 'main.js'),
	output: {
		path: path.join(__dirname, 'dist'),
		filename: 'bundle.js'
	},
	module: {
		loaders: [
			{
				test: path.join(__dirname, 'src'),
				loader: 'babel-loader',
				query: {
					cacheDirectory: 'babel-cache',
					presets: ['es2015', 'react']
				}
			}
		]
	}
};

The only change is in the presets array.
Note: We are NOT in the same folder than the last section! But I use the same folder names here. You can change them as you please.
Let’s write some React in our greetings.js :

Nothing crazy. Import React and create a component that iterates through the names array. Let’s write our entry file, main.js:

main.js

const React = require('react');
const ReactDOM = require('react-dom');
const Greetings = require('./greetings');

ReactDOM.render(, document.getElementById('main'));

This file imports the component Greetings and renders it inside the index.html.

Now, you need to run this command into your terminal to get all the necessary dependencies:

npm install webpack babel-core babel-loader babel-preset-es2015 react react-dom babel-preset-react

Compared to the last section, we added the react, react-dom and babel-preset-react dependencies.
Now you can run webpack in your terminal and open your index.html and you can see your magnificent component in your browser. Awesome!

Webpack is a very powerful tool that will become more and more useful as your applications grow. This article only describe a small portion of what Webpack is able to do. I believe it should be enough to be able to play around with it.
You can find more information on the Webpack documentation here.

As always, feel free to share, ask questions or correct me if I made a mistake.
Have a nice day!

Read more