‘Node Knoggin’ #303

Kevin Valias
8 min readAug 31, 2020

If a user attempts to create a resource that already exists — for example, an email address that’s already registered — what HTTP status code would you return?

-409 CONFLICT — — — The request could not be completed due to a conflict with the current state of the target resource. This code is used in situations where the user might be able to resolve the conflict and resubmit the request.

Consider a responsive site design that requires a full-width image in all responsive states. What would be the correct way to code this to ensure the page loads the smallest image required to fill the space?

-We can use two new attributes — srcset and sizes — to provide several additional source images along with hints to help the browser pick the right one.

<img srcset="elva-fairy-480w.jpg 480w,
elva-fairy-800w.jpg 800w"
sizes="(max-width: 600px) 480px,
800px"
src="elva-fairy-800w.jpg"
alt="Elva dressed as a fairy">

srcset defines the set of images we will allow the browser to choose between, and what size each image is. Each set of image information is separated from the previous one by a comma. For each one, we write:

  1. An image filename (elva-fairy-480w.jpg)
  2. A space
  3. The image’s intrinsic width in pixels (480w) — note that this uses the w unit, not px as you might expect. This is the image's real size, which can be found by inspecting the image file on your computer (for example, on a Mac you can select the image in Finder and press Cmd + I to bring up the info screen).

sizes defines a set of media conditions (e.g. screen widths) and indicates what image size would be best to choose, when certain media conditions are true — these are the hints we talked about earlier. In this case, before each comma we write:

  1. A media condition ((max-width:600px)) — you'll learn more about these in the CSS topic, but for now let's just say that a media condition describes a possible state that the screen can be in. In this case, we are saying "when the viewport width is 600 pixels or less".
  2. A space
  3. The width of the slot the image will fill when the media condition is true (480px)

So, with these attributes in place, the browser will:

  1. Look at its device width.
  2. Work out which media condition in the sizes list is the first one to be true.
  3. Look at the slot size given to that media query.
  4. Load the image referenced in the srcset list that has the same size as the slot or, if there isn't one, the first image that is bigger than the chosen slot size.

When should you npm and when should you yarn?

-Package Managers are a must-have tool for most developers mainly because it makes the development process so easy and a good package manager is just one less thing for the developer to worry about.

npm(node package manager) has been an extremely popular choice among developers evidenced by the amazingly increasing search trends at the almighty StackOverflow

-But a while ago, many developers faced issues with npm and tried creating alternatives for npm. The most prominent among these alternatives has been Yarn. It was released by Facebook in October 2016 as a tweaked version of npm covering some of its inefficiencies. In their very own words,

-Yarn is a package manager that doubles down as project manager. Whether you work on one-shot projects or large monorepos, as a hobbyist or an enterprise user, we’ve got you covered.

npm was also updated since then and is in a neck-to-neck competition with Yarn over which package manager is the best!

-But first, let’s see the drawbacks of npm by discussing how the need to develop Yarn rose. Although if you’re in a hurry and have idea about both package managers, you can rush to the Conclusion section in the end to get a brief comparison on major factors.

Note: In this blog, we will be discussing Yarn 1 and not the recently launched Yarn 2 as it was critiqued by many developers, and even Facebook has not adopted it yet.

Why was Yarn developed?

-Javascript saw a major boom of popularity this decade and therefore, naturally, npm was also used heavily by developers all around the world. Obviously this meant that tech giants relied on the then-developer-friendly package manager too, and one of them was Facebook! Needless to say, over time, the code-base grew larger which lead to several problems from efficiency problems to security issues.

-Soon, they decided to engineer their own package manager based on npm eliminating as many drawbacks of npm as they could. Thus, Yarn was born.

Yarn pulls packages from the official npm registry but the developers can download the repositories and manage them faster now using Yarn.

So what advantages does Yarn have over npm?

-The most significant and most popular advantage that Yarn has over npm is :

  • Incredible Speed: Yarn is several times faster than npm as it downloads the packages at incredible speed. The factors to its speed are:-

— Caching: It caches every package it has downloaded to avoid re-downloading it later when the need arises.

— Parallel execution: It parallelizes the operations allowing maximum utilization of resources and faster response time.

-Since the introduction of Yarn, there have been several updates on npm. The most distinguished update has been npm 5.0 and, launched quite recently, npm 6.0. It really tightened the competition between npm and Yarn mostly in terms of speed. But Yarn is still faster. We shall be discussing more about npm updates later in the blog.

-The other improvements made in Yarn were:-

  • npm and bower support: Yarn has backward compatibility towards both npm and bower registries.
  • Inclusion of yarn.lock: The lock file eliminates the possibility of having different versions installed across different devices. Basically, /node_modules are in perfect synchronization. Yarn only installs only using lockfiles which makes it secure against vulnerabilities experienced by npm which includes packages while executing. This also increases security.
  • Checksums: The lockfile also includes package checksums to check the integrity of every package(another factor for increased security).
  • Licensing: The content for licenses and disclaimers can be triggered using a command in cli. The licenses for installed modules can be restricted. This feature isn’t available in npm.
  • Offline mode: Previously downloaded packages can be reinstalled due to caching capability.
  • Duplicate Removal: Duplicates are eliminated by resolving mismatched versions of dependencies.
  • Workspaces: Quite useful for monorepo developers who like to store codes of multiple projects in one repository. Multiple project dependencies are handled in one workspace with one lockfile.
  • Upgrade: Yarn came up with a command yarn upgrade-interactive allowing a very developer-friendly interactive space to upgrade packages.

So Yarn is better than npm?

-Well, let’s not draw up conclusions too fast. npm did overcome many of its drawbacks since Yarn was developed. The most significant upgrades for npm were npm 5.0 and npm 6.0.

npm 5.0 and npm 6.0 has made a lot of improvements such as:-

  • Improved Speed: The latest updates on npm made the process of downloading packages much faster and comparable to Yarn (Yarn is still considered to be faster in most cases though).
  • Cache and Offline mode: Added and improved cache functionality allowing the offline mode.
  • Automatic Saving: The packages are automatically saved in memory. You can delete the packages when you no longer need it.
  • Included package-lock.json: Works similar to yarn.lock mentioned above.
  • npx: npx is used to run scripts from ./node_modules/.bin. It also has the ability to execute a package that wasn't previously installed(install it on-the-fly).

Note: You can also use npm-check module which works similar to yarn upgrade-interactive, but it doesn’t come packaged with npm so didn’t include it here.

Conclusion

-If you need a package manager, both npm and Yarn are excellent choices with a lot of benefits to you. Although different developers have different needs with their projects and are comfortable with different environments. We will try to help you though by providing a brief comparison of common consideration factors.

Speed: Although not by as a huge margin as before, Yarn is still faster than npm.

Stability: Both Yarn and npm are quite stable and accessible across multiple environments.

Usage and Support: npm has, by a large margin, higher usage compared to Yarn mainly due to it being a standard for a long time. It also has large community support.

-This is the comparison of npm downloads vs yarn downloads over the past 2 years

Security: npm still hasn’t addressed its security issues as well as Yarn. Therefore, Yarn has better security as explained above.

Repository: Yarn is compatible with both npm and bower repositories so that’s a point in Yarn’s favor.

-This should help you form a basic idea in your head about the works and differences between the two.

How can you make sure your dependencies are safe?

-First, it’s important to do our homework before installing a package.

-Read the package’s page on npmjs.com and look at who published the package, the number of versions and the number of weekly downloads. If these numbers are very low, I would pass or definitely inspect the source code.

-Another thing, to pay attention is when you type the package name. Typo squatting is possible and there are published packages which have names close to popular packages.

-In terms of how secure is NPM (the registry), they do periodic penetration testing and outgoing code reviews. Also, they report vulnerabilities to package authors and handle vulnerabilities reports from other users. But, it’s a continuous fight against spammers, malware, etc.

Commands you can run:

  • npm outdated (for locals) and npm outdated -g --depth=0 (for globals)
    This will check which packages are outdated and it will list "Current Wanted Latest" versions for each outdated package.
  • npm audit
    This will produce a report of security vulnerabilities with the affected package name, vulnerability severity and description, etc.

-Also, npm audit automatically runs when you install a package with npm install.

  • npm audit fix
    This automatically install compatible updates to vulnerable dependencies.

What are the differences between CHAR and VARCHAR data types (MySQL)?

  • The main difference between char and varchar is that char is a data type available in SQL that helps to store characters, while varchar is a data type available in SQL that helps to store variable characters.

How else can the JavaScript code below be written using Node.Js to produce the same output?

console.log("first");
setTimeout(function() {
console.log("second");
}, 0);
console.log("third");// Output:// first
// third
// second

So, the above code can be written in Node.js as:

console.log("first");
setImmediate(() => {
console.log("second");
});
console.log("third");

WHY?

setTimeout(fn, delay) calls the given callback fn after the given delay has ellapsed (in milliseconds). However, the callback is not executed immediately at this time, but added to the function queue so that it is executed as soon as possible, after all the currently executing and currently queued event handlers have completed. Setting the delay to 0 adds the callback to the queue immediately so that it is executed as soon as all currently-queued functions are finished.

setImmediate(fn) achieves the same effect, except that it doesn’t use the queue of functions. Instead, it checks the queue of I/O event handlers. If all I/O events in the current snapshot are processed, it executes the callback. It queues them immediately after the last I/O handler, somewhat like process.nextTick. This is faster than setTimeout(fn, 0).

Austin Coding Academy

--

--