About me

When it comes to programming, I’m a self-taught. No college, no coding bootcamp… I’m just a random French guy, in his room, in front of his laptop, trying to make sense of all this. I love it. I love learning new things, I love Javascript and NodeJS.
My journey began about a year ago, and now I’m looking for a job in this industry. Programming really changed my life. It changed the way I think and see the world. It’s not just a body of knowledge, but a way of thinking.

My proudest moment in this journey so far came when I completed the three FreeCodeCamp certifications. It felt amazing to achieve such a milestone, and it taught me a lot. But the most important thing I learned is not about programming. So, let me tell you a little story about my FreeCodeCamp experience.

My FreeCodeCamp Story

FreeCodeCamp is an open source community . The concept is simple. You complete a curriculum based on Javascript. You learn to work with jQuery, NodeJS, D3, React… You complete different challenges in order to claim three certificates (Front-End, Back-End, Data Visualization).
Once you do this, you are eligible to code for nonprofits. I discovered FreeCodeCamp about 9 months ago. The curriculum is long (1200 hours) and hard. It took me a while to get all three certifications and I hit many obstacles. The FCC curriculum, in my opinion, is as much about the skills you learn as it is about the mindset you must have. Because I had some experience working with Javascript and Jquery, the first challenges were just things I already knew how to do. I wasn’t learning anything new.

Then, It started to become more complicated. And when it does, that little voice in your head becomes louder:

‘Really? You thought you were good enough for this? No degree, no prior experience, stop hurting yourself, this is not for you.’

The first few times, I was able to complete the challenges, to keep pushing. But at one point, the challenges are not just complicated because of their logic, you also need to learn a library or a framework (looking at you React). What did I do when I couldn’t prove that little voice in my head wrong? Well, I started to doubt myself. I procrastinated. I stopped doing things out of my comfort zone because I wanted to feel better about myself and my abilities.

To me, this feeling was the strongest when I was trying to complete the Game of Life challenge. You can find the challenge here. Now, I struggled for the previous React challenges, but this one was just scary to me. It looked complicated. All those cells doing things by themselves? I can’t do that. No way. It took me a while to get around this. Everything felt impossible about this challenge. From the way to display the cells to how I was supposed to make them interact with one another… How do you quiet the little voice and just move forward?

Just learn enough

The first thing I did was to learn more about React. I realized that my lack of basic understanding of the library was a real problem. So I learned a little bit more. Not too much, just enough to start playing around. I think this is important, you just have to understand enough to mess around. Don’t drown in the technical terms at first. In this case, I just needed to understand a little about props and state. It started very innocently, I just wanted to click a cell and toggle its state, from dead to alive. Just a simple click event. No big deal. Then, I added a setTimeout function. Again, nothing extraordinary. But, very few steps at a time, I completed a user story, then an other one. And one day, I looked at my browser and saw this.

Yeah, I made it. All me. Wow! Is the code perfect? I’m pretty sure it’s not. Is there a better way to show the board? I would not be shocked if it was the case. I’m a 100% sure that a few weeks or months from now, I will come back to this pen and find the code ugly. But when I completed that challenge, this is not what was on my mind.

At that moment, I just learned something way more important than React or any kind of technology the programming industry has ever invented or will ever come up with. I understood how to work around my own limitations and lack of knowledge at a given moment.

I read countless of articles about programming, saying that everybody can become a developer and you don’t need a certain kind of brain. Well, now, I know it is true. I’m not a good developer yet. I don’t write good code yet. A lot of things about React and NodeJS are mysteries to me for now.
I don’t have a programming job yet. That’s the developer I am in October 2016. This developer won’t be the same next month, next year or the next decade. But my limitations today don’t define the kind of developer or person I can become. The mindset you have and the ability to learn by yourself defines what you will become.

When is a flower perfect?

This is the main thing I got from the FreeCodeCamp curriculum. I understood a lot of technical concepts. But more importantly, I understood how to be comfortable with my own lack of knowledge and expertise. I truly believe this is worth more than any programming concept. I will end this article with a quote from ‘The Practicing Mind’ by Thomas M. Sterner that gave the title of this post:

At what point in a flower’s life, from seed to full bloom, does it reach perfection?

By now, I’m sure you can guess that the answer is:
The flower is always perfect.

So, FreeCodeCamp, Thank you for this !

As always, let me know what you think. And feel free to share.
Have a nice day.

Read more

In this article, we will build together a simple command-line application using NodeJS.

We will make a very original (not really) ToDo application. In this application, you will be able to create a todo, update todos and remove todos. We will use a file-based storage, meaning our todos will be stored in a file. Considering the size of the project, I believe a database is not necessary.

What do we need?

We will only use the tools that NodeJS provides us out of the box. No packages, no npm to worry about.

We won’t need much actually. To interact with the command-line, we will use the process object. It is a global object that allows us to read and control the current NodeJS process. You can find more information about this here : Node Process Docs .
Process is a global, meaning it’s always available, no need to require() it.

Next, because we will implement a file-based storage, we need to read and write to a file. NodeJS gives us the filesystem module, known as ‘fs’. We do need to require it.

And, that’s all we need. The rest of the logic will be handle by regular Javascript, let’s get started!

1) Files

First, let’s create a directory. Go to your terminal and type

mkdir <nameOfYourNewFolder>

and press enter. Now, type

cd <nameOfYourNewFolder>

and then:

touch server.js todos.txt

Great, we have our files now.
Let’s open our text editor and create some todos in our todos.txt.

Here is my todos.txt:

Buy clothes|Feed the cat

Note: To differentiate each todo, I chose to separate them with a pipe character. This choice is totally up to you, choose whatever character you feel is appropriate.

2) Read Todos from file

Awesome, now how do we read those todos from our todos.txt and display them in the terminal?
Open server.js and type this.


process.stdin.setEncoding('utf-8');
const fs = require('fs');

//Read todo from file and display them
let todos = getTodosFromFile();
displayTodos(todos);

function getTodosFromFile(){
    let todos = fs.readFileSync('todos.txt', {encoding: 'utf-8'});
    return todos.split('|');
}

function displayTodos(todosArray){
    console.log('\n\nHere are your todos: \n\n');
    for(let i = 0; i < todosArray.length; i++){
    console.log(i + ') ' + todosArray[i]);
}

console.log('\n');
displayInstructions();
console.log('\n');
}

function displayInstructions(){
    console.log('Type quit to exit. Type create <todo> to add a new todo.\n',
    'Type update <index> <todo> to update a todo.\n',
    'Type delete <index> to delete a todo.');
}

Let me explain: the first line sets the encoding for the terminal, here utf-8(in this case, stdin is our terminal).
Next, we require our fs module.

Next, we have a few functions.

The first function getTodosFromFile retrieves the content of our todos.txt. To achieve this, we use the fs.readFileSync function. It takes 2 parameters, the path of the file we want to read, and an object of options. The file is in the same directory as server.js, so we just type ‘todos.txt’. For the options, I specified the encoding {encoding: ‘utf-8’}. Now, this fs.readFileSync returns a string. But, I decide to split this array with the ‘|’ character. That allows me to know where a todo string stops and starts.

Note: If you use a different character than ‘|’ , you’ll have to replace the appropriate character in the split method.

Awesome, we are now in possession of an array of todos. Let’s show them with the displayTodos function. As you can see, this function takes the array of todos and iterate through them. I added a few newlines characters (\n) for clarity.

The displayInstructions function gives the user informations about how to interact with the application.

Amazing, so let’s see how this works.
Go to your terminal and type

node server.js

And here you see your todos:


Here are your todos:
0) Buy clothes
1) Feed the cat

Type quit to exit. Type create <todo> to add a new todo.
Type update <index> <todo> to update a todo.
Type delete <index> to delete a todo.

Now, let’s add the different commands to create, update and delete todos.
We’ll start with creating.

3) Create todo

Right now, if you tried to type something in the console, nothing happens. You can only kill the process with Control + C. Why? Because we need to tell our process.stdin (terminal) what to do when we enter data.
In our displayInstructions function, you can see that we have 4 words that will be used as commands: quit, create, update and delete. Again, those are totally arbitrary.

So, our program needs to identify when the user enters data to the terminal, then our program needs to know if the text entered contains a special command. If the answer is yes, it triggers some actions depending on the command.

First things first, making our terminal listens to the data we type. To do this, we add this code:

process.stdin.on('data', (text)=>{
// our logic will go here
});

Each time we send data to the terminal, meaning each time we press Enter, the program will run the callback. The text parameter will be the string that you typed in the terminal. It will be a string because we set the encoding to ‘utf-8’ on the first line, remember?

Now, we need to now if the first word of the text is in fact a command. If we use a split method on the string and a switch statement, we can handle this problem like this:

process.stdin.on('data', (text)=>{
//split the string at the spaces
let textAsArray = text.split(' ');
let command = textAsArray[0];

switch(command){
    case 'create':
        //create Todo
        break;
    case 'update':
        //update Todo
        break;
    case 'delete':
        //delete Todo
        break;
    case 'quit\n':
        //exit program
        break;
    default:
        console.log('Unknown command.');
        displayInstructions();
    }
});

Each command has its own logic. If the command is not create, update, delete or quit, we use the displayInstructions function to help the user.

Note: You may notice the newline(\n) character after ‘quit’. When you type enter, the terminal seems to add this character automatically. Because the other commands needs additional input to their logic, if you just type ‘create’ or ‘delete’ or ‘update’, it will trigger the default case (because the terminal will add the newline character by default).

Very well, let’s write our logic for creating a Todo. The ‘create’ case will look like this:

case 'create':
    // Get todo text and update todos.txt
    let todoText = textAsArray.slice(1).join(' ');
    fs.appendFileSync('todos.txt', '|' + todoText);
    let todos = getTodosFromFile();
    displayTodos(todos);
    break;

First, we take away the command from the text. Remember, we split the string before the switch statement. So everything after the command is the body of our Todo. So we join the rest of the array with spaces.
Now, here is the fun part. We have our Todo as a string. We need to add it to our file todos.txt. To achieve this, we use fs.appendFileSync. It takes 2 parameters, the path of the file we want to write to, and the text we want to write. Notice that I add the ‘|’ character before the text of the Todo to help use differentiate todos in the future. After that, we use two functions that we already wrote earlier, getTodosFromFile and displayTodos. Now, after running this program, you will see your todos.txt updated and your new todo added in your terminal.

Note: Careful with the function you use to write to a file. Certain functions like fs.writeFileSync will replace the content of the file and not append. You can get more informations about the fs functions here: Node fs Docs

4)Update Todo

Awesome, now we can add todos to our little program. Let’s move on to updating.
If you read the instructions, you saw that the update command needs to be followed by the index of the todo you want to update, then by the new text of the todo. This means that we have to slice our array a bit more to retrieve the index. Here is how we could put this in place:

Add this inside the ‘update’ case:


case 'update':
    let indexUpdate = textAsArray[1];
    let newTodoText = textAsArray.slice(2).join(' ');
    if(isNaN(indexUpdate)){
        console.log('You must enter the index of the todo you want to update.');
    }else{
        updateTodo(indexUpdate, newTodoText);
    }
    break;

And here is the updateTodo function:

function updateTodo(index, todo){
    let todos = getTodosFromFile();
    if(index > todos.length -1 || index < 0){
        console.log('Index out of range');
        return;
    }
    todos[index] = todo;
    let updatedTodos = todos.join('|');
    fs.writeFileSync('todos.txt', updatedTodos);
    console.log('\nTodo Updated! \n ');
    displayTodos(todos);
}

Alright, let me break this down a bit. So we know the index is going to be at the second position in the textAsArray. This means everything after the index is the body of the updated Todo. We need to make sure the index is actually a number. If it is, we run the updateTodo function.
This function retrieves the todos first so we are up-to-date with the file. Next, we control that the index is in range. If it is, we update the correct todo. Then, as we did before with create, we write the new todos in our file. Finally, we display the new set of todos.

5)Delete Todo

We’re almost there! We now need to implement a way to delete a todo. To do this, we use the delete command followed by the index of the todo. Here is how the ‘delete’ case will look like:


case 'delete:
    let indexDelete = textAsArray[1];
    if(isNaN(indexDelete)){
        console.log('You must enter the index of the todo you want to delete.');
    }else{
        deleteTodo(indexDelete);
    }
    break;

And here is the deleteTodo function:

function deleteTodo(index){
    let todos = getTodosFromFile();
    if(index > todos.length -1 || index < 0){
        console.log('Index out of range');
        return;
    }
    todos.splice(index, 1);
    let updatedTodos = todos.join('|');
    fs.writeFileSync('todos.txt', updatedTodos);
    console.log('\nTodo Deleted!\n');
    displayTodos(todos);
}

Just like the update case, we retrieve the index and make sure it is a number. Then we call the deleteTodo function. We get up-to-date with the current todos and we make sure the index is not out of range. Then, a classic splice method on the todos array deletes the targeted todo. We join the array with our pipe ‘|’ character and write it to our file. Finally, we can display our todos.

6) Exit the program

Yeah! We can add, delete and update todos. We just need one more little thing: a way to exit the program. Now, if you know how to use the terminal, you will do control + C.But, our users may not know this trick. So we added the quit command. To do this, we add this logic to the ‘quit\n’ case:

case 'quit\n':
    console.log('Good Bye!');
    process.exit();

As you might have guessed, process.exit() kills the current process.

And there it is. We have a fun command-line application. You can run it with node server.js in your terminal.
You can get the full code here :
Code on GitHub

I hope everything was clear. Feel free to ask questions and share!
Have a nice day!

Read more

This blog is focused on Node.js. So, it only seems logical to start things off by trying to explain what NodeJS is. I will try my best to break down what this platform is all about and what it allows us to do.

You may have heard about NodeJS as: “Javascript on the server”. But can we dig deeper than that? Sure we can!

The Node.Js website (https://nodejs.org/eng) welcomes you with this paragraph:

“Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js’ package ecosystem, npm, is the largest ecosystem of open source libraries in the world.”

Alright, that’s a mouthful, let’s try to break this down!

First, “is a JavaScript runtime”. Yep, Node.Js is written in Javascript. The most popular language in the world  also runs this platform. This means developers can use the same language on the front-end AND the back-end.

Next, “uses an event-driven, non-blocking I/O model”.  What??

Node uses a event loop. This event loop handles dispatching events in your program. It handles requests and responses, and if there is none, the event loop is sleeping, just waiting for something to happen.

The non-blocking I/O (input/output) means that your program keeps running while the server processes a request.

So, if Node receives several requests, the server is able to handle them asynchronously. They all get treated as soon as they are received. The server doesn’t wait for a previous request to be completed to start a new one.
Conventional I/O model will use a blocking model, meaning the execution of the program stops while the request is being processed. There are ways to process several requests at the same time, but they are more demanding in resources and can cause latency.
Example: Reading data from a file with Node.Js

 const fs = require('fs');

//event loop receives this and is handled outside of the loop
 fs.readFile('/myfile.json', function(data){
 console.log(data);
 });
 //program keeps running
 //when the response comes back, the callback is executed

 

Next, we have ‘lightweight and efficient’.

It’s pretty self-explanatory. I suggest you visit NodeJS GitHub’s page (https://github.com/nodejs/node) and realize how small it is. And this is what I love about it. The freedom to do whatever you want with Node. Node doesn’t have an opinion, Node is just a platform, Node is not a framework. It gives you a foundation to build on. And that foundation is solid, but minimalist. So there are a lot of possibilities and this is what makes Node fast.

You may ask: “That’s great but, if Node is minimalist, how can there but so many possibilities?”

You add what we call packages with a tool called NPM. NPM is the Javascript’s package manager. Basically, the Javascript community build packages and they are accessible by everyone.

“Node.js’ package ecosystem, npm, is the largest ecosystem of open source libraries in the world.”

Just to give you an idea, there are more than 330 000 modules in the NPM library. I’m sure you can imagine the level of commitment from the Javascript community in this tool. Let alone all the ideas and possibilities that all those modules add to NodeJS.

Let me add a few more advantages about NodeJS:

  1. – JSON(JavaScript Object Notation) is a popular way to format data, and is native to Javascript.
  2. – Javascript is a language used in some NoSQL databases (MongoDB, CouchDB)
  3. – NodeJS use Google Chrome’s V8 Engine, which stays up-to-date with the Javascript language standards. Meaning, you don’t have to wait for your browsers to catch up with the javascript you are writing.

I hope you have a better understanding of what Node.Js is. The next logical question would be: What can I actually do with this?

  1. NodeJS is designed to handle real-time applications, what we call DIRT( Data-Intensive Real-Time). You can think of a chat room for example, or a multiplayer game. Socket.io is a popular tool is this regard.
  2. NodeJS is also perfectly able to handle Web Applications. You may have heard of the Express framework.
  3. Command Line Applications
  4. APIs (Application Programming Interface)

I’m going to leave you with a snippet of code that create a http server with Node. You’ll see how little code you actually need.

const http = require('http');
 http.createServer(function(request, response){
 response.writeHead(200, { 'Content-Type' : 'text/plain'});
 response.end('Hello World\n');
 }).listen(3000);
 console.log('Magic happening at http://localhost:3000');

 

First, we require the http module, which Node provides out of the box.
Then, we create a server. The callback is run every time the server receives a request. It takes two arguments, request and response.
We define the type of data that our response will send (here just text/plain). We then end the response sending ‘Hello World’. Finally, we tell our server to listen to port 3000.
To start the server, go to your terminal, and type node <fileName>. You will see “Hello World” at http://localhost:3000 and the console.log message in your terminal.

That’s it!
I hope I have been clear enough in my explanations. Feel free to ask questions or correct me if I made some mistakes.
Feel free to share!

Sources:

Read more