October 2016

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

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