Wednesday, August 14, 2019

How to minify images with Gulp & gulp-imagemin

Images are everywhere across the internet. You would be hard pressed to find a single page or application that doesn’t contain at least one image in some form or another. Images are great way to help tell stories and emphasize critical parts of our lives.
But if you’re like me you know that having a large image can seriously impact the performance of your site/app. So today, I’m going to teach you how to use Gulp and an npm package called gulp-imagemin to reduce the size of your images on the fly.
If you don’t know what all of these words mean, fear not! I have some relevant and important links/descriptions below to help bring you up to speed.
  • Minification, or minifying as I like to call it, is the act or process of removing unnecessary parts of source code to reduce size.
  • Gulp is a JavaScript build tool that allows you to automate parts of your workflow to streamline your process. It takes care of some not so interesting, but important, aspects of your workflow (like reducing image size) so that you can focus on the building. You can find Gulp here.
  • To make use of npm we'll need to install Node.js which is, in a nutshell, the framework that allows developers to use JavaScript code in a server (back end) environment. You can find Node here.
  • npm (Node Package Manager) is and does what its name implies. It is a package manager for JavaScript and "the world's largest software registry". Just think of npm as a giant storage area for awesome packages/utilities to help developers. You can find npm here.
  • gulp-imagemin is one of those awesome packages I mentioned earlier. Using this package we'll be able to automatically reduce the size of our images every time a save occurs. You can find gulp-imagemin here.
Alright, now that explanations are out of the way let’s get to the fun parts :D

Project File Structure

Start by opening up your text editor of choice and creating a directory for your project or if you have an existing directory navigate to that directory in your terminal and skip down to the Installing Node & npm Section.
If you’re using VS Code you can find the built in terminal by hitting ctrl + ` (tilde).
Here’s how my project structure looks in my terminal:
And here’s how my project file structure looks in the explorer inside VS Code:
As you can see I have a separate directory for my base files and the minified files. Once you have your project directory established it’s time to start installing everything we’ll need.

Installing Node & npm

Alright, now that our directory is up and running let’s start installing our dependencies. If you already have Node & npm installed, feel free to skip down to the Installing Gulp & gulp-imagemin Section.
  1. First, enter node --v within your terminal to check and see if you have the Node installed. If you do, you'll get something back like v8.9.3
  2. If you get nothing back or an error, simply download and install Node from here. It could take a few minutes so +be patient.
  3. Once Node.js is installed, you'll have npm installed as well because it comes bundled with Node. You can check the version of npm by typing npm -v in your terminal. You should get something like 6.4.1back.
  4. Next we need to create a package.json file for our project. We do this by using the command npm init (find out more about package.json here). You'll be asked a series of questions but if you don't want to answer them you don't have to, just hit enter until you see Is this OK? (yes), then hit Enter one last time and you'll be finished with this section.
You’ll notice that this file was created in a different directory than the one I started with. This is so I can provide an example, as I have previously installed all of this in my current project directory.

Installing Gulp & gulp-imagemin

Once Node & npm have been installed, we can now install Gulp & gulp-imagemin by following these steps:
  1. First, type npm install --save-dev gulp in your terminal. If you want to know what the --save-dev flag does, check out this Stack Overflow post.
  2. Again, be patient as installing Gulp might take a minute but you’ll eventually end up with something like this: gulp@4.0.0 added 318 packages from 218 contributors and audited 6376 packages in 49.362s found 0 vulnerabilities
  3. You can check your Gulp version by typing gulp -v in your terminal and you'll get something similar to this: [13:06:56] CLI version 2.0.1 [13:06:56] Local version 4.0.0
  4. Now let’s install gulp-imagemin by typing npm install --save-dev gulp-imagemin and again you'll get something like this back: gulp-imagemin@5.0.3added 232 packages from 97 contributors and audited 10669 packages in 39.103s found 0 vulnerabilities
  5. And the final step for this section is to create our gulpfile.js It is very important that your file has this exact name and is in the outer most level of your project folder structure!

Writing the Code — Finally the Fun!

Ok, now that we’ve taken care of installing everything in the correct place, let’s open up our gulpfile.js and write the actual code that will do all of the hard work.
  1. Start by requiring gulp --> const gulp = require('gulp');We're basically taking advantage of Node's module system to use code that is located in different files
  2. Now require gulp-imagemin --> const imagemin = require('gulp-imagemin'); Again we're taking advantage of the module system to use this code in our project
  3. Now, we need to write the function that will do all of the image squashing: 
    function imgSquash() {
    return gulp .src("./img/*")
    .pipe(imagemin()) 
    .pipe(gulp.dest("./minified/images"));
    }
  4. If you set your directory up following mine, the code above will work. If your directory looks different you will need to change the .src & .dest lines to match where your files are located and where you want them piped to after they've been minified.
  5. Gulp operates based off of tasks and we can give it plenty of those to keep it busy. Once we've defined the actual function to do the heavy lifting, we need to tell Gulp what to do with that function: gulp.task("imgSquash", imgSquash);
  6. Now, we want Gulp to watch our given directory for changes (new images) and when it detects those, we want it to automatically run our imgSquash function, minify our images, and pipe them to the destination we set. We achieve that by defining another task to watch the directory: 
    gulp.task("watch", () => { 
    gulp.watch("./img/*", imgSquash);
    });
  7. The last step to writing the code is defining the last task to call our imgSquashand watch tasks in succession:gulp.task("default",gulp.series("imgSquash","watch")); Here the word "default" refers to the word gulp in the terminal and the gulp.series will ensure that the imgSquash function runs and immediately after Gulp will watch the directory for changes.
Here is what our finished file should look like:
Save this file, open your terminal, and type gulp and hit enter. You should see something like this:
As you can see, each time a new file was added to the base directory, our tasks kicked in because Gulp was watching and immediately ran our imgSquash function to minify our images. When you're finished using Gulp you can hit ctrl + c in your terminal to terminate the watch process.
Now you can start using your minified images on your website/app and enjoy that new found boost in performance!

Wrap Up

Gulp is a very powerful JavaScript build tool that can help automate some of the more tedious, but important, aspects of building your project. With less than an hour’s worth of work you were able to get your images minified, thus reducing load time and increasing performance for your website/app. That’s awesome and you should be proud of yourself!
This is just one of the many ways that build tools like Gulp can help you. There are many more ways it can help (minifying/concatenating CSS/JS files) and I hope you explore some of those awesome options.
If you enjoyed this article please consider donating some claps as it helps others find my work. Also, drop a comment and let me know what you’re working on and how Gulp helps you focus on the building.
And finally, this article was originally posted on my personal blog. While you’re there don’t forget to sign up for the Newsletter which can be found at the top right corner of my blog page. I send it out monthly (I promise not to spam your inbox) and it’s filled with awesome articles from across the web that I think you’ll find helpful.
As always, have an awesome day full of love, happiness, and coding!

Thursday, July 4, 2019

Vấn đề với nodemon

Vấn đề:
nodemon chỉ restart lại express server khi mình thay đổi các file .js hoặc .html
với các file template (vd ejs, pug, hbs...) thì nó không refresh
Giải pháp:
cách 1: mở app.js và control+s để lưu lại, sẽ kích hoạt restart server
cách 2:
nodemon app.js -e js,hbs,ejs,pug

Monday, July 1, 2019

ECMAScript 2015 (ES6) and beyond

Node.js is built against modern versions of V8. By keeping up-to-date with the latest releases of this engine, we ensure new features from the JavaScript ECMA-262 specificationare brought to Node.js developers in a timely manner, as well as continued performance and stability improvements.
All ECMAScript 2015 (ES6) features are split into three groups for shippingstaged, and in progress features:
  • All shipping features, which V8 considers stable, are turned on by default on Node.jsand do NOT require any kind of runtime flag.
  • Staged features, which are almost-completed features that are not considered stable by the V8 team, require a runtime flag: --harmony.
  • In progress features can be activated individually by their respective harmony flag, although this is highly discouraged unless for testing purposes. Note: these flags are exposed by V8 and will potentially change without any deprecation notice.

Which features ship with which Node.js version by default?

The website node.green provides an excellent overview over supported ECMAScript features in various versions of Node.js, based on kangax's compat-table.

Which features are in progress?

New features are constantly being added to the V8 engine. Generally speaking, expect them to land on a future Node.js release, although timing is unknown.
You may list all the in progress features available on each Node.js release by grepping through the --v8-options argument. Please note that these are incomplete and possibly broken features of V8, so use them at your own risk:
node --v8-options | grep "in progress"

What about the performance of a particular feature?

The V8 team is constantly working to improve the performance of new language features to eventually reach parity with their transpiled or native counterparts in EcmaScript 5 and earlier. The current progress there is tracked on the website six-speed, which shows the performance of ES2015 and ESNext features compared to their native ES5 counterparts.
The work on optimizing features introduced with ES2015 and beyond is coordinated via a performance plan, where the V8 team gathers and coordinates areas that need improvement, and design documents to tackle those problems.

I have my infrastructure set up to leverage the --harmony flag. Should I remove it?

The current behaviour of the --harmony flag on Node.js is to enable staged features only. After all, it is now a synonym of --es_staging. As mentioned above, these are completed features that have not been considered stable yet. If you want to play safe, especially on production environments, consider removing this runtime flag until it ships by default on V8 and, consequently, on Node.js. If you keep this enabled, you should be prepared for further Node.js upgrades to break your code if V8 changes their semantics to more closely follow the standard.

How do I find which version of V8 ships with a particular version of Node.js?

Node.js provides a simple way to list all dependencies and respective versions that ship with a specific binary through the process global object. In case of the V8 engine, type the following in your terminal to retrieve its version:
node -p process.versions.v8

Sunday, September 16, 2018

Cài đặt Nodejs cho Mac

download bản .pkg


This package has installed:
  • Node.js v8.11.2 to /usr/local/bin/node
  • npm v5.6.0 to /usr/local/bin/npm
Make sure that /usr/local/bin is in your $PATH.

Thursday, May 24, 2018

Cài đặt request

Go to directory of your project
mkdir TestProject
cd TestProject
Make this directory a root of your project (this will create a default package.json file)
npm init --yes
Install required npm module and save it as a project dependency (it will appear in package.json)
npm install request --save
Create a test.js file in project directory with code from package example
var request = require('request');
request('http://www.google.com', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body); // Print the google web page.
  }
});
Your project directory should look like this
TestProject/
- node_modules/
- package.json
- test.js
Now just run node inside your project directory
node test.js

Wednesday, May 23, 2018

Node.js Events W3Schools

Node.js is perfect for event-driven applications.

Events in Node.js

Every action on a computer is an event. Like when a connection is made or a file is opened.
Objects in Node.js can fire events, like the readStream object fires events when opening and closing a file:

Example

var fs = require('fs');
var rs = fs.createReadStream('./demofile.txt');
rs.on('open', function () {
  console.log('The file is open');
});

Events Module

Node.js has a built-in module, called "Events", where you can create-, fire-, and listen for- your own events.
To include the built-in Events module use the require() method. In addition, all event properties and methods are an instance of an EventEmitter object. To be able to access these properties and methods, create an EventEmitter object:
var events = require('events');
var eventEmitter = new events.EventEmitter();

The EventEmitter Object

You can assign event handlers to your own events with the EventEmitter object.
In the example below we have created a function that will be executed when a "scream" event is fired.
To fire an event, use the emit() method.

Example

var events = require('events');
var eventEmitter = new events.EventEmitter();

//Create an event handler:var myEventHandler = function () {
  console.log('I hear a scream!');
}

//Assign the event handler to an event:eventEmitter.on('scream', myEventHandler);

//Fire the 'scream' event:eventEmitter.emit('scream');

Node.js NPM W3schools

What is NPM?

NPM is a package manager for Node.js packages, or modules if you like.
www.npmjs.com hosts thousands of free packages to download and use.
The NPM program is installed on your computer when you install Node.js
NPM is already ready to run on your computer!

What is a Package?

A package in Node.js contains all the files you need for a module.
Modules are JavaScript libraries you can include in your project.

Download a Package

Downloading a package is very easy.
Open the command line interface and tell NPM to download the package you want.
I want to download a package called "upper-case":
Download "upper-case":
C:\Users\Your Name>npm install upper-case
Now you have downloaded and installed your first package!
NPM creates a folder named "node_modules", where the package will be placed. All packages you install in the future will be placed in this folder.
My project now has a folder structure like this:
C:\Users\My Name\node_modules\upper-case


Using a Package

Once the package is installed, it is ready to use.
Include the "upper-case" package the same way you include any other module:
var uc = require('upper-case');
Create a Node.js file that will convert the output "Hello World!" into upper-case letters:

Example

var http = require('http');
var uc = require('upper-case');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(uc("Hello World!"));
    res.end();
}).listen(8080);
Save the code above in a file called "demo_uppercase.js", and initiate the file:
Initiate demo_uppercase:
C:\Users\Your Name>node demo_uppercase.js
If you have followed the same steps on your computer, you will see the same result as the example: http://localhost:8080