Node.js 10.0 Fills Some Gaps, Polishes a Few Rough Edges

Node.js 10 was released this April and I just wanted to kind of touch on what’s new—the additions improvements, etc. Obviously, I’m not going go through the extensive change log or anything but I just want to mention the major things. The changes are so many that you’ll find this information in series of articles elsewhere but I figured that I would wrap it up in one article and try to convey it in a simple way.
I know these aren’t the most exciting articles to read and share in the world but if you’re a JavaScript developer or someone who works at a technology firm, I think it’s really important to keep up-to-date with these things. It’ll be a short article.


NPM Can Do That?

I have been using the NPM package manager for a few years and watched it rise, almost fall (to Yarn) and evolve into a fast, full-featured package manager and much more. Along the way there are a few simple tricks that have saved me a bunch of time.
Viewing Available NPM Scripts
Picture this… you finally find some time to work on that little app or side project. It’s been days or weeks since you last looked at the code. You open up Visual Studio Code, hit CTRL-` to open the integrated terminal and type npm…? Darn, you can’t remember the command to build/run/debug/do something to your app. Time to crack open the package.json and see how it all works. Buzz kill. Wait, what about…


Thoughts on Importing npm Modules to the Web as JavaScript Modules

I’ve got thoughts on the post I did about ES Modules.
“I needed a quick way import a simple module get-urls into my project. The module is well tested and it does what I needed … ignore the fact that it’s pretty easy to implement in a couple of lines of JavaScript. The problem I had is that my project is built in ES6, uses modules, and I didn’t want to have to bundle up using CommonJS (require).


Importing NPM Modules to the Web as ES6 Modules

I’ve been working on a way to make it easier to push content into my static site and it’s been a fun little exercise that I will share more in another post. In this post, I want to share the rollup config that I used to import nearly any NPM module into a front-end project using ES6 Modules.
I needed a quick way to import a simple module get-urls into my project. The module is well tested and it does what I needed… ignore the fact that it’s pretty easy to implement in a couple of lines of JavaScript. The problem I had is that my project is built in ES6, uses modules, and I didn’t want to have to bundle up using CommonJS (require).


The Wonderful Wide World of webpack: Unpacking Awesomeness

In the past couple of years, webpack has come a long way. It continues to rapidly evolve and revolutionize the way we bundle JavaScript and more. For some of us that have been doing development for more than a few years, seeing an amazing tool like webpack and all of its abilities is mind-blowing. If only it had come into existence a bit sooner…
If you’re like me, you may have stumbled across webpack, hearing about its gazillion configuration options, along with a bunch of plugins, numerous ways to optimize your bundle, and more. So much that it all makes your head spin and you begin to feel overwhelmed as you attempt to make sense of it. That’s honestly how my journey began with Webpack.


10 JavaScript Animation Libraries to Follow in 2018

The client-side of a modern day website feeds off quality animation, which has lead to a rise in the need for JavaScript animation libraries. Fortunately, the supply seems to have matched the demand and there are a lot of options out there. However, making a choice on which library to go with could cause a lot of headaches. A lot of libraries have the potential to become better over the course of the year and would be the go-to solutions for creating animations.
Let’s take a look at the top ten JavaScript animation libraries.


10 Must-have VS Code Extensions for JavaScript Developers

In this article, I’ll focus on must-have VS Code extensions for JavaScript developers.
Visual Studio Code is undoubtedly the most popular lightweight code editor today. It does borrow heavily from other popular code editors, mostly Sublime Text and Atom. However, its success mainly comes from its ability to provide better performance and stability. In addition, it also provides much needed features like IntelliSense, which were only available in full-sized IDEs like Eclipse or Visual Studio 2017.
The power of VS Code no doubt comes from the marketplace. Thanks to the wonderful open-source community, the editor is now capable of supporting almost every programming language, framework and development technology. Support for a library or framework comes in various ways, which mainly includes snippets, syntax highlighting, Emmet and IntelliSense features for that specific technology.
VS Code Extensions by Category
For this article, I’ll focus on VS Code extensions specifically targeting JavaScript developers. Currently, there are many VS Code extensions that fit this criterion, which of course means I won’t be able to mention all of them. Instead, I’ll highlight VS Code extensions that have gained popularity and those that are indispensable for JavaScript developers. For simplicity, I’ll group them into ten specific categories.
Snippet Extensions
When you first install VS Code, it comes with a several snippets for JavaScript and Typescript. Before you start writing modern JavaScript, you’ll need some additional snippets to help you quickly write repetitive ES6/ES7 code:

VS Code JavaScript (ES6) snippets: currently the most popular, with over 1.2 million installs to date. This extension provides ES6 syntax for JavaScript, TypeScript, HTML, React and Vue extensions.

JavaScript Snippet Pack: a collection of useful snippets for JavaScript.

Atom JavaScript Snippet: JavaScript snippets ported from the atom/language-javascript extension.

JavaScript Snippets: a collection of ES6 snippets. This extension has snippets for Mocha, Jasmine and other BDD testing frameworks.

Syntax Extensions
VS Code comes with pretty good syntax highlighting for JavaScript code. You can change the colors by installing themes. However, you need a syntax highlighter extension if you want a certain level of readability. Here are a couple of them:

JavaScript Atom Grammar: this extension replaces the JavaScript grammar in Visual Studio Code with the JavaScript grammar from the Atom editor.

Babel JavaScript: syntax highlighting for ES201x JavaScript, React, FlowType and GraphQL code.

DotENV: syntax highlighting for .env files. Handy if you’re working with Node.

Linter Extensions
Writing JavaScript code efficiently with minimum fuss requires a linter that enforces a specific standard style for all team members. ESLint is the most popular, since it supports many styles including Standard, Google and Airbnb. Here are the most popular linter plugins for Visual Studio Code:

ESLint: this extension integrates ESLint into VS Code. It’s the most popular linter extension, with over 6.7 million installs to date. Rules are configured in .eslintrc.json.

JSHint: a code checker extension for JSHint. Uses .jshintrcfile at the root of your project for configuration.

JavaScript Standard Style: a linter with zero configuration and rigid rules. Enforces the StandardJS Rules.

JSLint: linter extension for JSLint.

If you’d like an overview of available linters and their pros and cons, check out our comparison of JavaScript linting tools.
Node Extensions
Every JavaScript project needs to at least one Node package, unless you’re someone who likes doing things the hard way. Here are a few VS Code extensions that will help you work with Node modules more easily.

npm: uses package.jsonto validate installed packages. Ensures that the installed packages have the correct version numbers, highlights installed packages missing from package.json, and packages that haven’t been installed.

Node.js Modules IntelliSense: autocomplete for JavaScript and TypeScript modules in import statements.

Source: vscode-node-module-intellisense

Path IntelliSense: it’s not really Node related, but you definitely need IntelliSense for local files and this extension will autocomplete filenames.

Node exec: allows you to execute the current file or your selected code with Node.js.

View Node Package: quickly view a Node package source with this extension, which allows you to open a Node package repository/documentation straight from VS Code.

Node Readme: quickly open npm package documentation.

Search node_modules: this extension allows you to search the node_modules folder, which is usually excluded from standard search.

Source: vscode-search-node-modules

Import Cost: displays size of an imported package.

Source: import-cost

The post 10 Must-have VS Code Extensions for JavaScript Developers appeared first on SitePoint.


What’s new in ES2017: Async functions, improved objects and more

Let’s take a look at the most important JavaScript updates that came with ES2017, and also briefly cover how this updating process actually takes place.
The Update Process
JavaScript (ECMAScript) is an ever-evolving standard implemented by many vendors across multiple platforms. ES6 (ECMAScript 2015) was a large release which took six years to finalize. A new annual release process was formulated to streamline the process and rapidly add new features.
The modestly named Technical Committee 39 (TC39) consists of parties including browser vendors who meet to push JavaScript proposals along a strict progression path:
Stage 0: strawman –
An initial submission of ideas for new or improved ECMAScript features.
Stage 1: proposal –
A formal proposal document championed by at least one member of TC39, which includes API examples, language semantics, algorithms, potential obstacles, polyfills and demonstrations.
Stage 2: draft –
An initial version of the feature specification. Two experimental implementations of the feature are required, although one can be in a transpiler such as Babel.
Stage 3: candidate –
The proposal specification is reviewed and feedback is gathered from vendors.
Stage 4: finished –
The proposal is ready for inclusion in ECMAScript. A feature should only be considered a standard once it reaches this stage. However, it can take longer to ship in browsers and runtimes such as Node.js.
If ES2015 was too large, ES2016 was purposely tiny to prove the standardization process. Two new features were added:

The array .includes() method which returns true or false when a value is contained in an array, and
The a ** b exponentiation operator, which is identical to Math.pow(a, b).

What’s New in ES2017
The feature set for ES2017 (or ES8 in old money) is considered to be the first proper amendment to the ECMAScript specification. It delivers the following goods …
Async functions
Unlike most languages, JavaScript is asynchronous by default. Commands which can take any amount of time do not halt execution. That includes operations such as requesting a URL, reading a file, or updating a database. A callback function must be passed, which executes when the result of that operation is known.
This can lead to callback hell when a series of nested asynchronous functions must be executed in order. For example:
function doSomething() {
doSomething1((response1) => {
doSomething2(response1, (response2) => {
doSomething3(response2, (response3) => {
// etc…

ES2015 (ES6) introduced Promises, which provided a cleaner way to express the same functionality. Once your functions were Promisified, they could be executed using:
function doSomething() {

ES2017 Async functions expand on Promises to make asynchronous calls even clearer:
async function doSomething() {
response1 = await doSomething1(),
response2 = await doSomething2(response1),
response3 = await doSomething3(response2);

await effectively makes each call appear as though it’s synchronous while not holding up JavaScript’s single processing thread.
Async functions are supported in all modern browsers (not IE or Opera Mini) and Node.js 7.6+. They’ll change the way you write JavaScript, and a whole article could be dedicated to callbacks, Promises and Async functions. Fortunately, we have one! Refer to Flow Control in Modern JavaScript.
Continue reading %What’s new in ES2017: Async functions, improved objects and more%


Build a Simple Beginner App with Node, Bootstrap & MongoDB

If you’re just getting started with Node.js and want to try your hand at building a web app, things can often get a little overwhelming. Once you get beyond the “Hello, World!" tutorials, much of the material out there has you copy-pasting code, with little or no explanation as to what you’re doing or why.
This means that, by the time you’ve finished, you’ve built something nice and shiny, but you also have relatively few takeaways that you can apply to your next project.
In this tutorial, I’m going to take a slightly different approach. Starting from the ground up, I’ll demonstrate how to build a no-frills web app using Node.js, but instead of focusing on the end result, I’ll focus on a range of things you’re likely to encounter when building a real-world app. These include routing, templating, dealing with forms, interacting with a database and even basic authentication.
This won’t be a JavaScript 101. If that’s the kind of thing you’re after, look here. It will, however, be suitable for those people who feel reasonably confident with the JavaScript language, and who are looking to take their first steps in Node.js.
What We’ll Be Building
We’ll be using Node.js and the Express framework to build a simple registration form with basic validation, which persists its data to a MongoDB database. We’ll add a view to list successful registration, which we’ll protect with basic HTTP authentication, and we’ll use Bootstrap to add some styling. The tutorial is structured so that you can follow along step by step. However, if you’d like to jump ahead and see the end result, the code for this tutorial is also available on GitHub.
Basic Setup
Before we can start coding, we’ll need to get Node, npm and MongoDB installed on our machines. I won’t go into depth on the various installation instructions, but if you have any trouble getting set up, please leave a comment below, or visit our forums and ask for help there.
Many websites will recommend that you head to the official Node download page and grab the Node binaries for your system. While that works, I would suggest that you use a version manager instead. This is a program which allows you to install multiple versions of Node and switch between them at will. There are various advantages to using a version manager, for example it negates potential permission issues which would otherwise see you installing packages with admin rights.
If you fancy going the version manager route, please consult our quick tip: Install Multiple Versions of Node.js Using nvm. Otherwise, grab the correct binaries for your system from the link above and install those.
npm is a JavaScript package manager which comes bundled with Node, so no extra installation is necessary here. We’ll be making quite extensive use of npm throughout this tutorial, so if you’re in need of a refresher, please consult: A Beginner’s Guide to npm — the Node Package Manager.
MongoDB is a document database which stores data in flexible, JSON-like documents.
The quickest way to get up and running with Mongo is to use a service such as mLabs. They have a free sandbox plan which provides a single database with 496 MB of storage running on a shared virtual machine. This is more than adequate for a simple app with a handful of users. If this sounds like the best option for you, please consult their quick start guide.
You can also install Mongo locally. To do this, please visit the official download page and download the correct version of the community server for your operating system. There’s a link to detailed, OS-specific installation instructions beneath every download link, which you can consult if you run into trouble.
Although not strictly necessary for following along with this tutorial, you might also like to install Compass, the official GUI for MongoDB. This tool helps you visualize and manipulate your data, allowing you to interact with documents with full CRUD functionality.
At the time of writing, you’ll need to fill out your details to download Compass, but you won’t need to create an account.
Check that Everything is Installed Correctly
To check that Node and npm are installed correctly, open your terminal and type:
node -v

followed by:
npm -v

This will output the version number of each program (8.9.4 and 5.6.0 respectively at the time of writing).
If you installed Mongo locally, you can check the version number using:
mongo –version

This should output a bunch of information, including the version number (3.6.2 at the time of writing).
Check the Database Connection Using Compass
If you have installed Mongo locally, you start the server by typing the following command into a terminal:

Next, open Compass. You should be able to accept the defaults (server: localhost, port: 27017), press the CONNECT button, and establish a connection to the database server.

MongoDB Compass connected to localhost
Note that the databases admin and local are created automatically.
Using a Cloud-hosted Solution
If you’re using mLabs, create a database subscription (as described in their quick-start guide), then copy the connection details to the clipboard. This should be in the form:

When you open Compass, it will inform you that it has detected a MongoDB connection string and asks if you would like to use it to fill out the form. Click Yes, noting that you might need to adjust the username and password by hand. After that, click CONNECT and you should be off to the races.

MongoDB Compass connected to mLabs
Note that I called my database sp-node-article. You can call yours what you like.
Initialize the Application
With everything set up correctly, the first thing we need to do is initialize our new project. To do this, create a folder named demo-node-app, enter that directory and type the following in a terminal:
npm init -y

This will create and auto-populate a package.json file in the project root. We can use this file to specify our dependencies and to create various npm scripts, which will aid our development workflow.
Install Express
Express is a lightweight web application framework for Node.js, which provides us with a robust set of features for writing web apps. These features include such things as route handling, template engine integration and a middleware framework, which allows us to perform additional tasks on request and response objects. There is nothing you can do in Express that you couldn’t do in plain Node.js, but using Express means we don’t have to re-invent the wheel and reduces boilerplate.
So let’s install Express. To do this, run the following in your terminal:
npm install –save express

By passing the –save option to the npm install command, Express will be added to the dependencies section of the package.json file. This signals to anyone else running our code that Express is a package our app needs to function properly.
Install nodemon
nodemon is a convenience tool. It will watch the files in the directory it was started in, and if it detects any changes, it will automatically restart your Node application (meaning you don’t have to). In contrast to Express, nodemon is not something the app requires to function properly (it just aids us with development), so install it using:
npm install –save-dev nodemon

This will add nodemon to the dev-dependencies section of the package.json file.
Create Some Initial Files
We’re almost through with the setup. All we need to do now is create a couple of initial files before kicking off the app.
In the demo-node-app folder create an app.js file and a start.js file. Also create a routes folder, with an index.js file inside. After you’re done, things should look like this:
├── app.js
├── node_modules
│ └── …
├── package.json
├── routes
│ └── index.js
└── start.js

Now, let’s add some code to those files.
In app.js:
const express = require(‘express’);
const routes = require(‘./routes/index’);

const app = express();
app.use(‘/’, routes);

module.exports = app;

Here, we’re importing both the express module and (the export value of) our routes file into the application. The require function we’re using to do this is a built-in Node function which imports an object from another file or module. If you’d like a refresher on importing and exporting modules, read Understanding module.exports and exports in Node.js.
After that, we’re creating a new Express app using the express function and assigning it to an app variable. We then tell the app that, whenever it receives a request from forward slash anything, it should use the routes file.
Finally, we export our app variable so that it can be imported and used in other files.
In start.js:
const app = require(‘./app’);

const server = app.listen(3000, () => {
console.log(`Express is running on port ${server.address().port}`);

Here we’re importing the Express app we created in app.js (note that we can leave the .js off the file name in the require statement). We then tell our app to listen on port 3000 for incoming connections and output a message to the terminal to indicate that the server is running.
And in routes/index.js:
const express = require(‘express’);

const router = express.Router();

router.get(‘/’, (req, res) => {
res.send(‘It works!’);

module.exports = router;

Here, we’re importing Express into our routes file and then grabbing the router from it. We then use the router to respond to any requests to the root URL (in this case http://localhost:3000) with an “It works!” message.
Kick off the App
Finally, let’s add an npm script to make nodemon start watching our app. Change the scripts section of the package.json file to look like this:
"scripts": {
"watch": "nodemon ./start.js"

The scripts property of the package.json file is extremely useful, as it lets you specify arbitrary scripts to run in different scenarios. This means that you don’t have to repeatedly type out long-winded commands with a difficult-to-remember syntax. If you’d like to find out more about what npm scripts can do, read Give Grunt the Boot! A Guide to Using npm as a Build Tool.
Now, type npm run watch from the terminal and visit http://localhost:3000.
You should see “It works!”
Continue reading %Build a Simple Beginner App with Node, Bootstrap & MongoDB%


Create New Express.js Apps in Minutes with Express Generator

Express.js is a Node.js web framework that has gained immense popularity due to its simplicity. It has easy-to-use routing and simple support for view engines, putting it far ahead of the basic Node HTTP server.
However, starting a new Express application requires a certain amount of boilerplate code: starting a new server instance, configuring a view engine, setting up error handling.
Although there are various starter projects and boilerplates available, Express has its own command-line tool that makes it easy to start new apps, called the express-generator.
What is Express?
Express has a lot of features built in, and a lot more features you can get from other packages that integrate seamlessly, but there are three main things it does for you out of the box:

Routing. This is how /home /blog and /about all give you different pages. Express makes it easy for you to modularize this code by allowing you to put different routes in different files.
Middleware. If you’re new to the term, basically middleware is “software glue”. It accesses requests before your routes get them, allowing them to handle hard-to-do stuff like cookie parsing, file uploads, errors, and more.
Views. Views are how HTML pages are rendered with custom content. You pass in the data you want to be rendered and Express will render it with your given view engine.

Getting Started
Starting a new project with the Express generator is as simple as running a few commands:
npm install express-generator -g

This installs the Express generator as a global package, allowing you to run the express command in your terminal:
express myapp

This creates a new Express project called myapp which is then placed inside of the myapp directory.
cd myapp

If you’re unfamiliar with terminal commands, this one puts you inside of the myapp directory.
npm install

npm is the default Node.js package manager. Running npm install installs all dependencies for the project. By default, the express-generator includes several packages that are commonly used with an Express server.
The generator CLI takes half a dozen arguments, but the two most useful ones are the following:

-v . This lets you select a view engine to install. The default is jade. Although this still works, it has been deprecated in favor of pug.
-c . By default, the generator creates a very basic CSS file for you, but selecting a CSS engine will configure your new app with middleware to compile any of the above options.

Now that we’ve got our project set up and dependencies installed, we can start the new server by running the following:
npm start

Then browse to http://localhost:3000 in your browser.
Application Structure
The generated Express application starts off with four folders.
The bin folder contains the executable file that starts your app. It starts the server (on port 3000, if no alternative is supplied) and sets up some basic error handling. You don’t really need to worry about this file because npm start will run it for you.
The public folder is one of the important ones: ​everything​ in this folder is accessible to people connecting to your application. In this folder, you’ll put JavaScript, CSS, images, and other assets that people need when they connect to your website.
The routes folder is where you’ll put your router files. The generator creates two files, index.js and users.js, which serve as examples of how to separate out your application’s route configuration.
Usually, here you’ll have a different file for each major route on your website. So you might have files called blog.js, home.js, and/or about.js in this folder.
The views folder is where you have the files used by your templating engine. The generator will configure Express to look in here for a matching view when you call the render method.
Outside of these folders, there’s one file that you should know well.
Continue reading %Create New Express.js Apps in Minutes with Express Generator%