Friday, September 25, 2020

Use Imagemin to compress images

 

Why should you care? 

Uncompressed images bloat your pages with unnecessary bytes. The photo on the right is 40% smaller than the one on the left, yet would probably look identical to the average user.

20 KB

12 KB

Measure 

Run Lighthouse to check for opportunities to improve page load by compressing images. These opportunities are listed under "Efficiently encode images":

image

Lighthouse currently reports on opportunities to compress images in JPEG format only.

Imagemin 

Imagemin is an excellent choice for image compression because it supports a wide variety of image formats and is easily integrated with build scripts and build tools. Imagemin is available as both a CLI and an npm module. Generally, the npm module is the best choice because it offers more configuration options, but the CLI can be a decent alternative if you want to try Imagemin without touching any code.

Plugins 

Imagemin is built around "plugins." A plugin is an npm package that compresses a particular image format (e.g. "mozjpeg" compresses JPEGs). Popular image formats may have multiple plugins to pick from.

The most important thing to consider when choosing a plugin is whether it is "lossy" or "lossless." In lossless compression, no data is lost. Lossy compression reduces file size, but at the expense of possibly reducing image quality. If a plugin doesn't mention whether it is "lossy" or "lossless," you can tell by its API: if you can specify the image quality of the output, then it is "lossy."

For most people, lossy plugins are the best choice. They offer significantly greater filesize savings, and you can customize the compression levels to meet your needs. The table below lists popular Imagemin plugins. These aren't the only plugins available, but they'd all be good choices for your project.

Imagemin CLI 

The Imagemin CLI works with 5 different plugins: imagemin-gifsicle, imagemin-jpegtran, imagemin-optipng, imagemin-pngquant, and imagemin-svgo. Imagemin uses the appropriate plugin based on the image format of the input.

To compress the images in the "images/" directory and save them to the same directory, run the following command (overwrites the original files):

$ imagemin images/* --out-dir=images

Imagemin npm module 

If you use one of these build tools, checkout out the codelabs for Imaginemin with webpackgulp, or grunt.

You can also use Imagemin by itself as a Node script. This code uses the "imagemin-mozjpeg" plugin to compress JPEG files to a quality of 50 ('0' being the worst; '100' being the best):

const imagemin = require('imagemin');
const imageminMozjpeg = require('imagemin-mozjpeg');

(async() => {
const files = await imagemin(
['source_dir/*.jpg', 'another_dir/*.jpg'],
{
destination: 'destination_dir',
plugins: [imageminMozjpeg({quality: 50})]
}
);
console.log(files);
})();

How to serve static files

 A basic necessity for most http servers is to be able to serve static files. Thankfully, it is not that hard to do in Node.js. First you read the file, then you serve the file. Here is an example of a script that will serve the files in the current directory:

var fs = require('fs'),
    http = require('http');

http.createServer(function (req, res) {
  fs.readFile(__dirname + req.url, function (err,data) {
    if (err) {
      res.writeHead(404);
      res.end(JSON.stringify(err));
      return;
    }
    res.writeHead(200);
    res.end(data);
  });
}).listen(8080);

This example takes the path requested and it serves that path, relative to the local directory. This works fine as a quick solution; however, there are a few problems with this approach. First, this code does not correctly handle mime types. Additionally, a proper static file server should really be taking advantage of client side caching, and should send a "Not Modified" response if nothing has changed. Furthermore, there are security bugs that can enable a malicious user to break out of the current directory. (for example, GET /../../../).

Each of these can be addressed invidually without much difficulty. You can send the proper mime type header. You can figure how to utilize the client caches. You can take advantage of path.normalize to make sure that requests don't break out of the current directory. But why write all that code when you can just use someone else's library?

There is a good static file server called node-static written by Alexis Sellier which you can leverage. Here is a script which functions similarly to the previous one:

var static = require('node-static');
var http = require('http');

var file = new(static.Server)();

http.createServer(function (req, res) {
  file.serve(req, res);
}).listen(8080);

This is a fully functional file server that doesn't have any of the bugs previously mentioned. This is just the most basic set up, there are more things you can do if you look at the api. Also since it is an open source project, you can always modify it to your needs (and feel free to contribute back to the project!).

Wednesday, September 16, 2020

Cập nhật nodejs với nvm

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash
wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash
nvm ls // local node versions
nvm ls-remote // remote node versions
nvm install 12.8.8 // install node v12.8.8
nvm use 10.6.7 // switch to node v10.6.7

Monday, September 14, 2020

Nodejs Starter - Javascript Boilerplates to start fast

 Hello Coders,

Usually, when we start a new project, the codebase tends to repeat over and over among different projects. Instead of reinventing the wheel, all the time can be a good solution to use a starter kit, already equipped with a few basic tools and features.

This article presents a shortlist with Node.js starters qualified for production use, based on a few necessary characteristics:

  • clean code structure that follows proper coding standards
  • documented
  • actively supported
  • a minimum validation (Github Stars, Number of Downloads)
  • open source
  • permissive license ( MIT, Apache )

In my opinion, this shortlist with requirements qualifies a NodeJS starter to become a real candidate for a production app.

This list includes only a few Nodejs starters, used by me in different projects in the last 2 years. If you know a new killer project, unlisted here, please suggest it in the comments. Thank you!


Nodejs Starter / Vue Argon Design

Nodejs Starter - Vue Argon Design is a Full-Stack Nodejs starter equipped with a fully usable Vue.js UI, coded on top of the Argon Design System design. The app uses a decoupled architecture, where the Vue.js frontend communicates with the Nodejs through secure ajax calls.

Nodejs Starter, React Material Kit - Gif animated intro.


Nodejs Starter / React Material Kit

Nodejs Starter - React Material Kit is a Full-Stack Nodejs starter equipped with a fully usable React UI, coded on top of the Material Kit design. The app uses a decoupled architecture, where the React frontend communicates with the Nodejs through secure ajax calls.

Nodejs Starter, React Material Kit - Gif animated intro.


Nodejs Starter Hackathon

Nodejs Starter Hackathon is a project with 26k+ stars on Github, equipped with many useful features like:

  • MVC structure
  • Authentification: local (user/pass), OAuth (1.0, 2.0)
  • SaaS stylesheets, Bootstrap4 integrated
  • Forms powered by Mailgun and Sendgrid
  • Integrations for Paypal, Twitter, LinkedIn

This starter can be overwhelming for a beginner, but this fact can be easily compensated by reading the docs and interact with the project community.

Nodejs Starter hackathon - Image


Nodejs Starter API Kit

Nodejs Starter API Kit is a Boilerplate for authoring data API backends with Node.js and GraphQL. With more than 2.8k Github starts, this boilerplate is definitively a winner if your future project replaces the old school REST API with GraphQL. Features:

  • Common Node.js stack: Express, Passport, Session, Cors
  • PostgresSQL as DMBS, along with Redis
  • Localization and translations
  • Nodemailer, Handlebars templating
  • Deployment: via Docker

Starter Links


Nodejs Starter Serverless

Nodejs Starter Serverless is a Node.js starter for the Serverless Framework with async/await and unit test support. The project is actively supported by Frank Wang with 450 Github stars. This starter got my attention mainly for the serverless concept, which is a rising concept in web development nowadays. Features:

  • Integrate serverless-webpack plugin
  • ES7 syntax in handler functions
  • Support for unit tests (via Jtest)

Nodejs Starter Serverless Live sample hosted on AWS, and a sample of the code executed when we click on the link:

export const hello = async (event, context) => {
  return {
    statusCode: 200,
    body: JSON.stringify({
      message: `Go Serverless v1.0! ${(await message({ time: 1, copy: 'Your function executed successfully!'}))}`,
      input: event,
    }),
  };
};

const message = ({ time, ...rest }) => new Promise((resolve, reject) =>
  setTimeout(() => {
    resolve(`${rest.copy} (with a delay)`);
  }, time * 1000)
);

To start playing with this Nodejs starter, here is the list with requirements:


Nodejs Starter Express Bootstrap

Nodejs Starter Express Bootstrap is a lightweight Bootstrap NodeJS boilerplate built with ExpressJS 4, MongoDB/Mongoose, Authentication with Passport.js, Jade and GruntJS as Task Automation.

The app is well organized and actively supported by a freelancer. The demo link, hosted on Heroku, seems to be dead. The app can be successfully built on (at least) on Windows10 and Ubuntu 18.04.

Not here production-ready Nodejs starter you know? Please suggest in the comments.


Resources

Thank you!

The Best Node.js Boilerplate to Speed Up Your Project Development

 

What is Boilerplate?

Boilerplate is the term used to describe sections of code that can be included in many places with little or no alteration. It is more often used when referring to languages which are considered verbose, i.e. the programmer must write a lot of code to do minimal jobs. Boilerplate code is a piece of code which can be used over and over again or we can say it, a piece of reusable code.

Listing
Here is a list of boilerplate code you should consider when starting your Node.js project:

  1. Sahat Boilerplate

The first is Sahat boilerplate. Sahat for Node.js web applications is the most complete boilerplate and comes with a complex package. Sahat makes it as generic and reusable as possible to cover most use cases of hackathon web apps, without being too specific. In the worst case, you can use this as a learning guide for your projects. They have over 24k stars on GitHub.

2. Kriasoft Boilerplate

Kriasoft creates a Node.js API starter; this is a boiler and a tool for creating API data backend with Node.js, GraphQL, and bundle with Docker. This boilerplate is the most suitable for developing the GraphQL API endpoint. It can be built as an independent microservice or for creating a web front-end back-up and mobile application. If you are interested in GraphQL, this boilerplate is recommend to start your project.

3. Madhums’ Boilerplate

Madhums’ boilerplate is a boilerplate application for building web apps using Express, Mongoose, and Passport. Madhums’ boilerplate comes with MVC base pattern to implement the project. If you are familiar with MVC pattern it can be easier to switch from another language to Node.js

4. Icebob Boilerplate

Icebob boilerplate is a full-stack web app boilerplate project with VueJS, ExpressJS, and MongoDB. Inspired by Sahat boilerplate, it focused on a starter project which contains common functions like user signup, login, OAuth, and user profile. So, we can create a new web app and only need to develop the business logic.

5. Talyssonoc Node API boilerplate

The last one is Talyssonoc Node API boilerplate. This boilerplate was built for creating backend API. The folder structure and logical architecture of this boilerplate focused on the separation of concerns based on domain-driven design and clean architecture. Instead of using the MVC pattern, this boilerplate has layers inside the src folder. Each of the folder layers is scoping by a namespace on the concern it is about (like the user, errors, logging and so on). For detailed information about the structure behind the boilerplate, read this. Unlike the others, this API base boilerplate by Talyssonoc is the simplest way to install the API project.


Recap

All boilerplates have advantages and disadvantages, each depending on the type of project. You can choose Sahat or Icebob to create an application with back end and front end support. Talyssonoc, Kriasoft, or Madhums boilerplate is suitable to create an API back end. You can choose Madhums boilerplate if you’re familiar with the MVC pattern, but if you’re looking for clean architecture and scalability, go for Talyssonoc.