Monthly Archives: June 2018

Debugging Node Code in VS Code

By James Quick

Visual Studio Code has an amazing amount of functionality built in, including support for debugging applications. Although the functionality is there, it took me several tries to figure out how to get things configured to debug Node applications. It became even more tricky when using Nodemon, so I figured it was worth it to share the various configurations I’ve learned. This article will not dive deep into inspecting variables, call stack, etc. but will focus more on the actual configurations. If you are looking for an article more focused on applied debuggging concepts, check out Debugging JavaScript in Chrome and Visual Studio Code.

Watch on YouTube

TLDR – Debugging Node in Visual Studio Code

  • Download Debugger for Chrome extension
  • Create Debug configuration from one of the 4 below
  • Launch Debug configuration
  • Set breakpoints, inspect variables, etc.

Setup

For this article, I’m giong to be debugging an application called ‘Quick Chat’.

While it is not required for you to run the same application, you can easily follow this video series to build the application yourself or clone the source code if you choose.

After choosing an application to Debug, you will need to install the ‘Debugger for Chrome’ extension.

With that taken care of let’s create a breakpoint in our app. The Quick Chat application is a simple Node/Express app that uses Socket.io to allow users to chat with each other in real time. Therefore, I decided to add a breakpoint where a client connects to our server. As you can see in the screenshot below, I’ve created a breakpoint (the red circle) just inside the function that gets called each time a user gets connected. For reference, to create a breakpoint in VS Code, click in the gutter, or empty space, to the left of the line numbers. Regardless of what application you are debugging, set a breakpoint that can be triggered easily (ex. when the application loads, a route is triggered, etc.).

To create a breakpoint in VS Code, click in the gutter, or empty space, to the left of the line numbers

VS Code Debugging Panel

To open the Debug panel, click on the bug looking icon on the sidebar (on the left side by default). I won’t dive too deep into this, but notice quickly that there are four different sections: variables, watch, call stack, and breakpoints.

Again, for more background into what these sections mean, check out [Debugging JavaScript in Chrome and Visual Studio Code]().

At the top of the panel you will see a green play button and a dropdown that says ‘No Configurations’ if you have yet to create a debug configuration. If you have already created a configuation, you’ll see it listed there. The great thing about creating these debug configurations is that VS Code is happy to help.

VS Code stores debug configurations in a file called launch.json inside of a folder .vscode. VS Code helps us not only create that folder and file, but also helps to generate predefined configurations as well. Let’s take a look at creating our first one.

To create your initial launch.json file, click the ‘No Configurations’ dropdown and choose ‘Add Configuration’. From here, ignore the popup and we will get started creating our first configuration.

Key Components of a Debug Configuration

  • name – the name of the configuration as displayed in the configurations dropdown
  • request – the type of action that you want to take
  • type (Node, Chrome, PHP, etc.)

As you create different configurations, VS Code will also provide intellisense for other properties that can be defined.

Debug Configuration 1 (Launch Node Program)

This first configuration will launch our Node application for us in debug mode. Running in debug mode means that VS Code will be able to connect to our app over a specific port for debugging. For this configuration, we mainly need to define the program file that will be run. The configuration looks like this.

To run this configuration, choose it from the configurations dropdown list, and click the green play/run button. You’re debug action bar will pop up in the top right with step, continue, restart, and stop buttons.

One thing you might have noticed is the warning I’ve got in my debug console. It mentioned that node --debug has been deprecated. Honestly, I’m not sure if this is VS Code’s fault or the version of Node that I have. Either way, there’s one thing to remember. To start a Node application in debug mode going forward, use the --inspect flag.

To start a Node application in debug mode going forward, use the --inspect flag.

Debug Configuration 2 (Attach by Process ID)

The second configuration, we’ll look at is attaching to a Node process by id. For this, we will need to start our Node server ourselves before running the debug configuration. Use the following command to start your server (using –inspect as mentioned above) and replace app.js with the name of your server file.

node --inspect app.js

With your server started, now you can run your debug configuration. When prompted, choose Node process that corresponds to the command we just ran to start our server.

Successfully connected!

Debug Configuration 3 (Attach to Port)

For our third configuration, we will be attaching to an existing Node application running on a given port. 9229 is the default port for debugging when using the --inspect flag so that’s what we’re going to use. Since we’ve already started our server with the previous configuration, we can just start our debug configuration. Choose “Attach to Port” configuration and click play!

Debug Configuration 4 (Attach to Port with Nodemon)

For our final configuration, we are going to tweak the previous one to support auto reloading with Nodemon. Before I explain what Nodemon is, it’s important to know that I consider this the most useful configuration in my day to day development.

Nodemon is a package, typically installed globally from NPM, that will auto reload your Node server as you save your files

For those of your who don’t know, Nodemon is a package, typically installed globally from NPM, that will auto reload your Node server as you save your files. This is incredibly useful as your are making changes and testing at the same time. I almost always run my Node application with Nodemon during development, and I would recommend you do too.

To install Nodemon, use the following command.

npm install -g nodemon

Because Nodemon will auto restart our server, in the debug configuration, we’ve set the restart property to true. This way, our debugger will reconnect when our server restarts. To test this out, run your server using this command (replacing node, from earlier, with nodemon). Obviously, make sure that you canceled your previously running server.

nodemon --inspect app.js

Then, run your configuration.

Keep in mind, we are using Nodemon. So, if we make a change to our server file and save it, our server will automatically be reloaded. Thankfully, we’ve defined our debug configuration to handle this scenario and reconnect as well. Make a small change to your file, save it, and make sure that your debugger reconnects when the server restarts.

Wrap Up

As I mentioned earlier, getting started debugging in VS Code took me a bit to figure out. The main issue I had was defining configurations appropriately, which is why I created this article. I hope that this gives you guys a clear idea of the available configurations when debugging Node in VS Code.

If you have any follow up questions or comments, leave one below of find me on twitter @jamesqquick.

Source:: scotch.io

Debugging Node Code in VS Code

By James Quick

Visual Studio Code has an amazing amount of functionality built in, including support for debugging applications. Although the functionality is there, it took me several tries to figure out how to get things configured to debug Node applications. It became even more tricky when using Nodemon, so I figured it was worth it to share the various configurations I’ve learned. This article will not dive deep into inspecting variables, call stack, etc. but will focus more on the actual configurations. If you are looking for an article more focused on applied debuggging concepts, check out Debugging JavaScript in Chrome and Visual Studio Code.

https://youtu.be/yFtU6_UaOtA

Watch on YouTube

TLDR – Debugging Node in Visual Studio Code

  • Download Debugger for Chrome extension
  • Create Debug configuration from one of the 4 below
  • Launch Debug configuration
  • Set breakpoints, inspect variables, etc.

Setup

For this article, I’m giong to be debugging an application called ‘Quick Chat’.

While it is not required for you to run the same application, you can easily follow this video series to build the application yourself or clone the source code if you choose.

After choosing an application to Debug, you will need to install the ‘Debugger for Chrome’ extension.

With that taken care of let’s create a breakpoint in our app. The Quick Chat application is a simple Node/Express app that uses Socket.io to allow users to chat with each other in real time. Therefore, I decided to add a breakpoint where a client connects to our server. As you can see in the screenshot below, I’ve created a breakpoint (the red circle) just inside the function that gets called each time a user gets connected. For reference, to create a breakpoint in VS Code, click in the gutter, or empty space, to the left of the line numbers. Regardless of what application you are debugging, set a breakpoint that can be triggered easily (ex. when the application loads, a route is triggered, etc.).

To create a breakpoint in VS Code, click in the gutter, or empty space, to the left of the line numbers

VS Code Debugging Panel

To open the Debug panel, click on the bug looking icon on the sidebar (on the left side by default). I won’t dive too deep into this, but notice quickly that there are four different sections: variables, watch, call stack, and breakpoints.

Again, for more background into what these sections mean, check out [Debugging JavaScript in Chrome and Visual Studio Code]().

At the top of the panel you will see a green play button and a dropdown that says ‘No Configurations’ if you have yet to create a debug configuration. If you have already created a configuation, you’ll see it listed there. The great thing about creating these debug configurations is that VS Code is happy to help.

VS Code stores debug configurations in a file called launch.json inside of a folder .vscode. VS Code helps us not only create that folder and file, but also helps to generate predefined configurations as well. Let’s take a look at creating our first one.

To create your initial launch.json file, click the ‘No Configurations’ dropdown and choose ‘Add Configuration’. From here, ignore the popup and we will get started creating our first configuration.

Key Components of a Debug Configuration

  • name – the name of the configuration as displayed in the configurations dropdown
  • request – the type of action that you want to take
  • type (Node, Chrome, PHP, etc.)

As you create different configurations, VS Code will also provide intellisense for other properties that can be defined.

Debug Configuration 1 (Launch Node Program)

This first configuration will launch our Node application for us in debug mode. Running in debug mode means that VS Code will be able to connect to our app over a specific port for debugging. For this configuration, we mainly need to define the program file that will be run. The configuration looks like this.

To run this configuration, choose it from the configurations dropdown list, and click the green play/run button. You’re debug action bar will pop up in the top right with step, continue, restart, and stop buttons.

One thing you might have noticed is the warning I’ve got in my debug console. It mentioned that node --debug has been deprecated. Honestly, I’m not sure if this is VS Code’s fault or the version of Node that I have. Either way, there’s one thing to remember. To start a Node application in debug mode going forward, use the --inspect flag.

To start a Node application in debug mode going forward, use the --inspect flag.

Debug Configuration 2 (Attach by Process ID)

The second configuration, we’ll look at is attaching to a Node process by id. For this, we will need to start our Node server ourselves before running the debug configuration. Use the following command to start your server (using –inspect as mentioned above) and replace app.js with the name of your server file.

node --inspect app.js

With your server started, now you can run your debug configuration. When prompted, choose Node process that corresponds to the command we just ran to start our server.

Successfully connected!

Debug Configuration 3 (Attach to Port)

For our third configuration, we will be attaching to an existing Node application running on a given port. 9229 is the default port for debugging when using the --inspect flag so that’s what we’re going to use. Since we’ve already started our server with the previous configuration, we can just start our debug configuration. Choose “Attach to Port” configuration and click play!

Debug Configuration 4 (Attach to Port with Nodemon)

For our final configuration, we are going to tweak the previous one to support auto reloading with Nodemon. Before I explain what Nodemon is, it’s important to know that I consider this the most useful configuration in my day to day development.

Nodemon is a package, typically installed globally from NPM, that will auto reload your Node server as you save your files

For those of your who don’t know, Nodemon is a package, typically installed globally from NPM, that will auto reload your Node server as you save your files. This is incredibly useful as your are making changes and testing at the same time. I almost always run my Node application with Nodemon during development, and I would recommend you do too.

To install Nodemon, use the following command.

npm install -g nodemon

Because Nodemon will auto restart our server, in the debug configuration, we’ve set the restart property to true. This way, our debugger will reconnect when our server restarts. To test this out, run your server using this command (replacing node, from earlier, with nodemon). Obviously, make sure that you canceled your previously running server.

nodemon --inspect app.js

Then, run your configuration.

Keep in mind, we are using Nodemon. So, if we make a change to our server file and save it, our server will automatically be reloaded. Thankfully, we’ve defined our debug configuration to handle this scenario and reconnect as well. Make a small change to your file, save it, and make sure that your debugger reconnects when the server restarts.

Wrap Up

As I mentioned earlier, getting started debugging in VS Code took me a bit to figure out. The main issue I had was defining configurations appropriately, which is why I created this article. I hope that this gives you guys a clear idea of the available configurations when debugging Node in VS Code.

If you have any follow up questions or comments, leave one below of find me on twitter @jamesqquick.

Source:: scotch.io

JavaScript Functional Programming (Solution to Code Challenge #11)

By William Imoh

Tried the code challenge #11? In that, we delved into solving basic array problems using array methods such as map(), reduce(), filter() etc.

You can find the awesome entries in the comment section of the post as well on Twitter using the hashtag #scotchchallenge. Also, you see some other fantastic submissions for the challenge if you check out the Scotch Slack Group as well as this Spectrum thread for the challenge.

The Challenge

Functional programming is a style in writing programs which utilizes functions and function evaluations to carry out computations.

In this challenge, we were tasked with solving problems by manipulating given arrays in a base codepen. This challenge will be solved using native array methods to manipulate the given array.

Methods are properties of a given data type which basically contains function definitions

With methods, we are basically applying pre-created functions on the array to achieve our desired result.

The Base

No HTML and CSS code is provided for this challenge as it requires no view. However, JavaScript code is provided containing the arrays to be manipulated – texasss, newieyork, and vegzas. Problems to be solved are also written in comments after each array.

While this challenge has no view, results will be logged to the console.

You can find the base codepen provided below.

The Technique

Basically solving the problems tied to each array is pretty straight-forward as we directly applied native array methods from:

  • filter()
  • map()
  • sort()
  • reduce()

Care is taken to understand which methods are mutating and also non-mutating

Mutating methods make changes to the original array whilst retaining the variable name whereas non-mutating methods create a new array with the result of the function application.

Array 1: texasss

On this array we are required to:

Find all users older than 24

This is done using the filter() function to return all objects whose age property value is less than 24. The result is logged to the console.

const users24 = texasss.filter(val => {
  return val.age > 24
});

console.log(users24)

Find the total age of all users

To solve this, first, we utilized the map() method to iterate through each object in the array, fetch the age of each user then use the reduce() method to sum up all the age values into a single value.

const totalAge = texasss.map((user)=> user.age).reduce((prev, next)=> prev + next)
console.log(totalAge)

List all users in the US

Similarly using the filter() option we traverse the array and fetch all users whose boolean value of the us property resolves to true.

const usersUS = texasss.filter(user => {
  return user.us == true;
})

console.log(usersUS)

Array 2: newieyork

In this array we’ll be taking things a bit further with:

List all users in US in ascending order

To achieve this we’ll use the sort() function. Sorting an array of objects using particular properties such as name or age can be tricky as compared to sorting array items with strings.

For us to sort the array, we will be creating a comparison function first converts the name values to be enumerated to lowercase. A ternary operator is used to conditionally return a value depending on which enumerable property is higher when compared.

const sortedUS = newieyork

sortedUS.sort((a, b) => {
  const x = a.name.toLowerCase()
  const y = b.name.toLowerCase()
  return x < y ? -1 : 1 
})

console.log(sortedUS)

Sort all users by age

Sorting all users by age is more straightforward as enumerating numerical values are quite simpler. The sort() method is used to arrange the users according to their age.

const sortedAge = newieyork

sortedAge.sort((a, b) => {
  return a.age - b.age
})

console.log(sortedAge)

List all female coders

In order to solve this, we employ the filter() function to pick out all users with the gender of f.

const femaleCoders = newieyork.filter(val=>{
  return val.gender == 'f'
})

console.log(femaleCoders)

Array 3: vegzas

Taking it one step further again, we’ll be solving the last set of challenges.

Find the total age of male coders under 25

To achieve this we employ three levels of function application, the steps are:

  • Filter the array to match gender and age requirements of m and 25 respectively.
  • Traverse the array and return the age of each user.
  • Find the sum of all the age fetched.
const maleCodersAge = vegzas
  .filter(val => val.gender == 'm' && val.age < 25)
  .map(male => male.age)
  .reduce((prev, next)=> prev + next)

console.log(maleCodersAge)

List all male coders over 30

Here we filter the array and return users with a gender of m and over the age of 30.

const maleCodersOver30 = vegzas.filter(val => {
  return val.age > 30 && val.gender == 'm'
})

console.log(maleCodersOver30)

Find the total age of everyone in texasss, newieyork and vegzas combined.

Down to the last challenge, we are required to find the total age of all the users in all the arrays. We achieved this by:

  • Creating an empty array to hold all the age of all users from all the arrays.
  • Traverse each array using the map() method and return the age of each user.
  • Add each age fetched into the empty array created using the push() method.
  • Use the reduce() method to sum all the ages pushed into the now populated array.
const totalAges = []

texasss.map(val => totalAges.push(val.age))
newieyork.map(val => totalAges.push(val.age))
vegzas.map(val => totalAges.push(val.age))

const ageSum = totalAges.reduce((prev, next)=> prev + next)
console.log(ageSum)

You can find the final product here: https://codepen.io/Chuloo/pen/JZWVPJ

Conclusion

In this challenge, we used various in-built array methods to solve these challenges. You can try out other array methods and functions, also dig the difference between methods with similar capabilities. Feel free to leave your comments and suggestions in the comment section of this post and watch out for the next challenge. Happy coding!

Source:: scotch.io

What the heck is "Script error?"

By Ryan Goldman

If you’ve done any work with the JavaScript onerror event before, you’ve probably come across the following:

"Script error."

“Script error” is what browsers send to the onerror callback when an error originates from a JavaScript file served from a different origin (different domain, port, or protocol). It’s painful because, even though there’s an error occurring, you don’t know what the error is, nor from which code it’s originating. And that’s the whole purpose of window.onerror — getting insight into uncaught errors in your application.

The cause: cross-origin scripts

To better understand what’s going on, consider the following example HTML document, hypothetically served from http://example.com/test:

<!doctype html>
<html>
<head>
  <title>example.com/test</title>
</head>
<body>
  <script src="http://another-domain.com/app.js"></script>
  <script>
  window.onerror = function (message, url, line, column, error) {
    console.log(message, url, line, column, error);
  }
  foo(); // call function declared in app.js
  </script>
</body>
</html>

Here’s the contents of http://another-domain.com/app.js. It declares a single function, foo , whose invocation will always throw a ReferenceError.

// another-domain.com/app.js
function foo() {
  bar(); // ReferenceError: bar is not a function
}

When this document is loaded in the browser, and JavaScript is executed, the following is output to the console (logged via the window.onerror callback):

"Script error.", "", 0, 0, undefined

This isn’t a JavaScript bug — browsers intentionally hide errors originating from script files from different origins for security reasons. It’s to avoid a script unintentionally leaking potentially sensitive information to an onerror callback that it doesn’t control. For this reason, browsers only give window.onerror insight into errors originating from the same domain. All we know is that an error occurred — nothing else!

I’m not a bad person, really!

Despite browsers’ good intentions, there are some really good reasons why you want insight into errors thrown from scripts served from different origins:

  1. Your application JavaScript files are served from a different hostname (e.g., static.sentry.io/app.js).
  2. You are using libraries served from a community CDN, like cdnjs or Google’s Hosted Libraries.
  3. You’re working with a commercial third-party JavaScript library that is only served from external servers.

But don’t worry! Getting insight into a JavaScript error served by these files only requires a few simple tweaks.

The fix: CORS attributes and headers

In order to get visibility into a JavaScript exception thrown by scripts originating from different origins, you must do two things.

1. Add a crossorigin=”anonymous” script attribute

<script src="http://another-domain.com/app.js" crossorigin="anonymous"></script>

This tells the browser that the target file should be fetched “anonymously.” This means that no potentially user-identifying information like cookies or HTTP credentials will be transmitted by the browser to the server when requesting this file.

2. Add a cross-origin HTTP header

Access-Control-Allow-Origin: *

CORS is short for Cross Origin Resource Sharing, and it’s a set of APIs (mostly HTTP headers) that dictate how files ought to be downloaded and served across origins.
By setting Access-Control-Allow-Origin: *, the server is indicating to browsers that any origin can fetch this file. Alternatively, you can restrict it to only a known origin you control:

Access-Control-Allow-Origin: https://www.example.com

Note: most community CDNs properly set an Access-Control-Allow-Origin header:

$ curl --head https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.js | 
    grep -i "access-control-allow-origin"

Access-Control-Allow-Origin: *

Once both of these steps have been made, any errors triggered by this script will report to window.onerror, just like any regular same-domain script. So, instead of “Script error,” the onerror example from the beginning would yield:

"ReferenceError: bar is not defined", "http://another-domain.com/app.js", 2, 1, [Object Error]

Boom! You’re done. ”Script error” will plague you and your team no more.

An alternative solution: try/catch

Sometimes we’re not in a position to adjust the HTTP headers of scripts our web application is consuming. In those situations, there’s an alternative approach: using try/catch.

Consider the original example again, this time with try/catch:

<!-- note: crossorigin="anonymous" intentionally absent -->
<script src="http://another-domain.com/app.js"></script>
<script>
window.onerror = function (message, url, line, column, error) {
  console.log(message, url, line, column, error);
}

try {
  foo(); // call function declared in app.js
} catch (e) {
  console.log(e);
  throw e; // intentionally re-throw (caught by window.onerror)
}
</script>

For posterity, some-domain.com/app.js once again looks like this:

// another-domain.com/app.js
function foo() {
  bar(); // ReferenceError: bar is not a function
}

Running the example HTML will output the following two entries to the console:

=> ReferenceError: bar is not defined
     at foo (http://another-domain.com/b.js:2:3)
     at http://example.com/test/:15:3

=> "Script error.", "", 0, 0, undefined

The first console statement — from try/catch — managed to get an error object complete with type, message, and stack trace, including file names and line numbers. The second console statement from window.onerror, once again, can only output “Script error.”

Now, does this mean you need to try/catch all of your code? Probably not. If you can easily change your HTML and specify CORS headers on your CDNs, it’s preferable to do so and stick to window.onerror.

But, if you don’t control those resources, using try/catch to wrap third-party code is a surefire (albeit tedious) way to get insight into errors thrown by cross-origin scripts.

Note: by default, raven.js, Sentry’s JavaScript SDK, carefully instruments built-in methods to try to automatically wrap your code in try/catch blocks. It does this to attempt to capture error messages and stack traces from all your scripts, regardless of which origin they’re served from. It’s still recommended to set CORS attributes and headers if possible.

Of course, there are plenty of commercial and open-source tools that do all the heavy-lifting of client-side reporting for you. (Psst: you might want to try Sentry to debug JavaScript.)

That’s it! Happy error monitoring.

Source:: scotch.io

Getting Started With Google Cloud Functions and MongoDB

By Valeri Karpov

Serverless architectures are becoming increasingly popular, and with good reason. In my experience, container-based orchestration frameworks have a steep learning curve and are overkill for most consumer-facing companies. With FaaS architectures, like AWS Lambda and Azure Functions, in theory the
only devops you need is bundling and uploading your app.

This article will walk you through setting up a Google Cloud Function in Node.js that connects to MongoDB. However, one major limitation of stateless functions is the need to establish a separate database connection every time the stateless function runs, which incurs a major performance penalty.

Unfortunately, I haven’t been able to figure out how to reuse a database connection in Google Cloud Functions, the trick that works for IBM Cloud, Azure Functions, and AWS Lambda does not work for Google Cloud Functions.

“Hello, World” in Google Cloud Functions

Go to the Google Cloud Functions landing page and click “Try it free”.

Click on the hamburger icon in the upper left and find the “Cloud Functions” link in the sidebar, then click “Create function”.

Name your function “hello-world” and leave the rest of the options in the “Create function” form unchanged. Leave “Function to execute” as “helloWorld”, because that needs to match the name of the function your code exports. Below is the code you should enter in, so you can confirm what version of Node.js your function is running on.

exports.helloWorld = (req, res) => {
  res.send(<span class="hljs-string">'Hello from Node.js '</span> + process.version);
};

Click “Create” and wait for Google to deploy your cloud function. Once your function is deployed, click on it to display the function’s details.

Click the “Trigger” tab to find your cloud function’s URL.

Copy the URL and use curl to run your cloud function.

$ curl https://us-central1-test21-201718.cloudfunctions.net/hello-world
Hello from Node.js v6.11.5
$

Google Cloud Functions don’t give you any control over what version of Node.js you run, they run Node.js v6.11.5 currently. You can’t use async/await natively on Google Cloud Functions at the time of this writing.

Connecting to MongoDB Atlas

Click on the “Source” tab in the function details and hit the “Edit” button. You’ll notice there’s 2 files in your source code, one of which is package.json. Edit package.json to match the below code.

{
  "name": "sample-http",
  "version": "0.0.1",
  "dependencies": {
    "co": "4.6.0",
    "mongodb": "3.x"
  }
}

Once you redeploy, Google Cloud will automatically install your npm dependencies for you. Now, change your index.js to match the below code, replacing the uri with your MongoDB Atlas URI.

const co = require('co');
const mongodb = require('mongodb');

const uri = 'ATLAS_URI_HERE';

exports.helloWorld = (req, res) => {
  co(function*() {
    const client = yield mongodb.MongoClient.connect(uri);

    const docs = yield client.db('test').collection('tests').find().toArray();
    res.send('Result: ' + JSON.stringify(docs));
  }).catch(error => {
    res.send('Error: ' + error.toString());
  });
};

Click “Save” to deploy your function. Once it is deployed, you should be able to curl your cloud function and get a document from MongoDB Atlas back.

$ curl https://us-central1-test21-201718.cloudfunctions.net/hello-world
Result: [{"_id":"5a7b7df69d07887542605888","name":"Hello!","__v":0}]
$

At this point, you would try re-using the database connection using the same
global state trick that works in AWS Lambda and other cloud function providers.

const co = require('co');
const mongodb = require('mongodb');

const uri = 'ATLAS_URI_HERE';

// Other cloud providers would retain this, but not Google Cloud
let client = null;

exports.helloWorld = (req, res) => {
  co(function*() {
    const reusedConnection = client != null;
    if (client == null) {
      client = yield mongodb.MongoClient.connect(uri);   
    }

    const docs = yield client.db('test').collection('tests').find().toArray();
    res.send('Result: ' + JSON.stringify(docs) + ', Reused: ' + reusedConnection);
  }).catch(error => {
    res.send('Error: ' + error.toString());
  })
};

Unfortunately, the global state trick doesn’t seem to work in Google Cloud.

$ curl https://us-central1-test21-201718.cloudfunctions.net/hello-world
Result: [{"_id":"5a7b7df69d07887542605888","name":"Hello!","__v":0}], Reused: false
$
$ curl https://us-central1-test21-201718.cloudfunctions.net/hello-world
Result: [{"_id":"5a7b7df69d07887542605888","name":"Hello!","__v":0}], Reused: false
$

Moving On

FaaS is a powerful paradigm, but purely stateless functions suffer from performance limitations when dealing with databases because establishing a new database connection is costly. Most cloud function providers have a mechanism for retaining database connections between function calls, but apparently Google Cloud Functions does not. This severely limits Google Cloud Functions’ ability to serve as a replacement for a conventional web server.

Source:: scotch.io

Weekly Node.js Update - #25 - 06.22, 2018

By Tamas Kadlecsik

Weekly Node.js Update - #25 - 06.22, 2018

Below you can find RisingStack‘s collection of the most important Node.js news, updates, projects & tutorials from this week:

Node v10.5.0 (Current) Released

Notable Changes:

  • crypto:
    • Support for crypto.scrypt() has been added.
  • fs:
    • BigInt support has been added to fs.stat and fs.watchFile.
    • APIs that take mode as arguments no longer throw on values larger than 0o777.
    • Fix crashes in closed event watchers.
  • Worker Threads:
    • Support for multi-threading has been added behind the –experimental-worker flag in the worker_threads module. This feature is experimental and may receive breaking changes at any time.

How to make beautiful, simple CLI apps with Node

When merging/rebasing, the file that always seems to cause trouble is the package-lock. In this post you’ll go through how to make a simple utility that deletes the package-lock.json file, regenerates it (npm install) and adds it to the git index.

JavaScript Engine V8 release v6.8

The newest branch of the Javascript Engine, V8 version 6.8 was announced. It is in beta until its release in coordination with Chrome 68 Stable.

End-to-end testing Single Page Apps and Node.js APIs with Cucumber.js and Puppeteer

In this article you’ll learn how to test Single Page Apps in an end-to-end fashion, using a Behavior-Driven-Development tool called Cucumber.js, and Google’s web browser library Puppeteer.

The minimal Node.js with Babel Setup

This article shows you a common approach of how to create a running minimal Node.js application with Babel. It also provides a good foundation for getting started with JavaScript, building Node.js projects on top of it, or releasing it as node package on npm as open source project.

Weekly Node.js Update - #25 - 06.22, 2018

Deploying Node.js Apps

In this document, you’ll learn the exact specifications and behavior of Node.js deployments running on now.

Quickstart: Control a device connected to an IoT hub (Node.js)

In this quickstart, you use a direct method to control a simulated device connected to your IoT hub. You can use direct methods to remotely change the behavior of a device connected to your IoT hub.

Previous Node.js Updates:

In the previous Weekly Node.js Update, we collected great articles, like

  • Node.js Updates from June 12;
  • Google Cloud announces support for Node.js in App Engine;
  • Deploying Node.js on App Engine standard environment;
  • AWS SDK for Node.js Best Practices;

& more…

We help you to stay up-to-date with Node.js on a daily basis too. Check out our Node.js news page and its Twitter feed!

Source:: risingstack.com

Building a Fancy Countdown Timer with MomentumSlider.js

By Luis Manuel

Original design by Oleg Frolov

Nowadays there are many Javascript libraries to make it easy the task of adding sliders to a website. Most have a host of features, to adapt the slider to the particular needs of each case. However, despite having so many functionalities, sometimes the sliders lack features that would result in a much better user experience.

In the case of sliders that implemented the drag and drop functionality, it is hard to see how almost none (not to be absolute) implements the ability to continue the movement that the user has started, adding momentum and deceleration as necessary.

In this tutorial we will introduce a new library, specifically to develop sliders with momentum in a simple way. Also we will create a fancy countdown timer, using this excellent design by Oleg Frolov as inspiration:

The final result will be the following:

Fancy Countdown Timer

If you want to know how to implement it, just keep reading 🙂

Introducing MomentumSlider

Before starting to implement our countdown timer component, let’s see what the new library MomentumSlider can do for us.

As its name suggests, the main functionality of this new library is to create sliders with momentum, although it also contains the basic functionalities of a common slider.

It has no dependencies, so to start using it we just have to include it in the HTML and create a new instance of MomentumSlider. Something like:

var mySlider = new MomentumSlider({
    el: '.container', // HTML element to append the slider
    range: [1, 5]     // Autogenerated number range
});

As you can figure out, the previous code is intended to generate a slider of numbers using the defined range, and include it within the .container element.

Of course, not all sliders are number ranges, so we can also provide custom elements for our slider, for which we must provide an HTML structure like the following:

<div class="container">
    <!-- Slider container -->
    <div class="ms-container ms-container--horizontal">
        <!-- Slider track -->
        <ul class="ms-track">
            <!-- Slider slides -->
            <li class="ms-slide">1</li>
            <li class="ms-slide">2</li>
            <li class="ms-slide">3</li>
            <li class="ms-slide">4</li>
            <li class="ms-slide">5</li>
        </ul>
    </div>
</div>

And then create a new instance of MomentumSlider in this way:

var mySlider = new MomentumSlider({
    el: '.ms-container' // HTML element to init a slider
});

The final result of this second example will be exactly the same as in the first, which we have done on purpose to illustrate how HTML is generated in the first case. The advantage of this second example is that within each .ms-slide element we can put anything 🙂

On the other hand, the general styles and dimensions of the slider must be specified in the CSS code. The library will work using those dimensions, which gives a lot of possibilities for customization.

So, after this brief introduction to our new library to develop sliders with momentum, we can begin to develop our countdown component.

HTML Structure

Let’s start with the necessary HTML code:

<!-- Mobile container -->
<main class="container">
    <!-- Progress bar -->
    <div class="progress"></div>
    <!-- Countdown counter -->
    <div class="counter">1</div>
    <!-- Button to toggle countdown -->
    <button class="button">Toggle</button>
</main>

As we can see it is a piece of code quite simple. We have not even had to add the numbers for the slider manually, since they will be generated in the Javascript.

Adding Styles

Now we will add the general styles to match the original design:

body {
  overflow: hidden;

  // Decorative background
  &:before {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    border-left: 50vw solid #FF6E6E;
    border-right: 50vw solid #FF6E6E;
    border-top: 50vh solid #354051;
    border-bottom: 50vh solid #354051;
    z-index: -1;
  }
}

// Mobile container
.container {
  position: absolute;
  left: 50%;
  top: 50%;
  width: 340px;
  height: 540px;
  background-color: #354051;
  box-shadow: 0 0 100px rgba(0, 0, 0, 0.5);
  transform: translate(-50%, -50%);
  overflow: hidden;

  // Header bar, just an aesthetic detail
  &:before {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 25px;
    background-color: rgba(0, 0, 0, 0.2);
    z-index: 3;
  }
}

Then we can add the styles needed for the slider. The most important styles here are those designed to position the slider elements, as well as some other styles to achieve the look and feel we want:

// Slider dimmensions
$ms-container-width: 340px;
$ms-slide-width: 125px;
$ms-slide-height: 540px;

// Slider container
.ms-container {
  position: relative;
  top: 50%;
  width: $ms-container-width;
  max-width: 100%;
  margin: 0 auto;
  overflow: hidden;
  transform: translateY(-50%);
}

// Slider track
.ms-track {
  position: relative;
  left: calc(50% - #{$ms-slide-width / 2}); // Centering
  white-space: nowrap;
  font-size: 0;
  list-style: none;
  padding: 0;
  margin: 0;
  will-change: transform;
}

// Slides
.ms-slide {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: $ms-slide-width;
  height: $ms-slide-height;
  font-size: 100px;
  font-family: 'Roboto Mono', monospace;
  color: #FFFFFF;
  user-select: none;
  will-change: transform;
}

To finish with our slider we need to add the gradient effect to smoothly hide the slides adjacent to the current slide. We get that with a pair of pseudo-elements from the .ms-container element. Let’s see the code:

// Slider container
.ms-container {

  // Gradients to hide the adjacent numbers smoothly
  &:before, &:after {
    content: '';
    position: absolute;
    top: 0;
    width: 80px;
    height: 100%;
    z-index: 1;
    pointer-events: none;
  }
  &:before {
    left: 0;
    background-image: linear-gradient(to right, rgba(53, 64, 81, 1) 25%, rgba(53, 64, 81, 0));
  }
  &:after {
    right: 0;
    background-image: linear-gradient(to left, rgba(53, 64, 81, 1) 25%, rgba(53, 64, 81, 0));
  }
}

And we’re done with the styles for the slider!

Adding Interactivity with Javascript

We already have our slider looking great, we just need to use our library MomentumSlider to add the necessary functionality. Let’s see how we can do it in the following piece of code:

// Initializing the slider
var ms = new MomentumSlider({
    el: '.container', // HTML element to append the slider
    range: [1, 60],   // Generate the elements of the slider using the range of numbers defined
    loop: 2,          // Make the slider infinite, adding 2 extra elements at each end
    style: {
        // Styles to interpolate as we move the slider
        // The first value corresponds to the adjacent elements
        // The second value corresponds to the current element
        transform: [{scale: [0.4, 1]}],
        opacity: [0.3, 1]
    }
});

Surely you have noticed that the previous code is simple, except perhaps for the style option. That is why we are going to explain a bit more about what this option is for.

The style option allows you to interpolate CSS styles as the slider is moved. Each property to be interpolated receives an Array value, in which the first value corresponds to the previous adjacent slide, the second value corresponds to the current slide, and the third value corresponds to the subsequent adjacent slide. In the absence of a third value (as in our case), the first value will be used instead.

In this way, you can achieve very nice effects, like the one we have achieved in our countdown timer 🙂

Implementing the Countdown

So far we have seen how to create our slider from scratch. Now let’s see how to add a simple countdown functionality.

In order to avoid making the tutorial too long, we are going to skip the necessary CSS code to achieve the final result we want to show. However, we think it is important to highlight how we have implemented the countdown timer functionality.

First we will listen the click event on the Toggle button, and we will start or stop the countdown accordingly:

// Simple toggle functionality
button.addEventListener('click', function () {
    if (running) {
        stop();
    } else {
        start();
    }
    running = !running;
});

Of course, for everything to work properly we must implement the start and stop functions respectively. Let’s see the code, commented in detail for a better understanding:

// Start the countdown
function start() {
    // Disable the slider during countdown
    ms.disable();
    // Get current slide index, and set initial values
    seconds = ms.getCurrentIndex() + 1;
    counter.innerText = secondsInitial = seconds;
    root.style.setProperty('--progress', 0);
    // Add class to trigger CSS transitions for `running` state
    container.classList.add('container--running');
    // Set interval to update the component every second
    timer = setInterval(function () {
        // Update values
        counter.innerText = --seconds;
        root.style.setProperty('--progress', (secondsInitial - seconds) / secondsInitial * 100);
        // Stop countdown if it's finished
        if (!seconds) {
            stop();
            running = false;
        }
    }, 1000);
}

// Stop the countdown
function stop() {
    // Enable slider
    ms.enable();
    // Clear interval
    clearInterval(timer);
    // Reset progress
    root.style.setProperty('--progress', 100);
    // Remove `running` state
    container.classList.remove('container--running');
}

Finishing

And we have finished the essential parts of our fancy component! Check it out 🙂

Fancy Countdown Timer

In this tutorial we saw how to use the new MomentumSlider library to create amazing sliders. Please note that this library is still in development, so if you find an error or want to contribute, you can do so through the Github repository. Stay tunned!

And remember that in this tutorial we only explain the essential parts of our countdown timer. We invite you to check the full code on Github, or modify it and try new things in the Codepen demo.

We sincerely hope that you have enjoyed the tutorial and that it has been useful!

Source:: scotch.io

Debugging JavaScript in Google Chrome and Visual Studio Code

By James Quick

Learning to debug is an essential skill for taking the next step as a developer. It’s important to understand and leverage the vast array of tools that exist for a given languge. Unfortunately, debugging might not seem as obvious when working with JavaScript outside of a full-fledged IDE. At least not initially. Let’s take a look at getting started debugging JavaScript in the Google Chrome Dev Tools as well as my favorite text editor for Web Development, Visual Studio Code.

Watch on YouTube

https://youtu.be/AX7uybwukkk

TLDR – Debugging JavaScript in Chrome?

  • Open the ‘Sources’ tab
  • Inspect code
  • Set breakpoints, inspect variables, etc.

TLDR – Debugging JavaScript in Visual Studio Code?

  • Download the Debugger for Chrome extension
  • Create Debug configuration
  • Launch Debug configuration
  • Set breakpoints, inspect variables, etc.

Setup

For this article, I’m giong to be debugging an application called ‘Quick Chat’.

While it is not required for you to run the same application, you can easily follow this video series to build the application yourself or clone the source code if you choose.

Whatever project you decide to run, you’ll need to start it up. You can serve your applicatin from Node, like I’m doing, or from the Live Server extension for a simple static site. If you’re new to the Live Server extension, check out this getting started video.

With my project, I’ve added a tiny bug that fails to register who the user is after they’ve logged in. Technically speaking, I’m incorrectly grabbing the user’s username by referencing usernameInput.text instead of usernameInput.value. If I made this mistake in real life, my first instinct is to use console.log() to print out the DOM element reference (bad James….BAD JAMES), which isn’t all that help as you can see. If this is you’re first instinct also, don’t worry, that’s why you’re here!!

Debugging Basics

Let’s start with the basics. The idea of debugging is being able to (conditionally) trigger what are called breakpoints to pause the execution of your code. This provides you, the developer, the opportunity to look at the state of your application by inspecting variables for example. You can even take it a step further and ‘watch’ variables of your choosing, so that whenever your application gets paused, you can inspect them specifically. After triggering a breakpoint, you will typically have the following options.

  • continue execution of your program
  • step through your code line by line
  • step out of the current function that you are in
  • step into the next function call.

You’ll additionally have access to view the call stack. In other words, as functions call other functions in your program, you can inspect the history of those function calls.

Debugging in Google Chrome

To get started with debugging in Chrome, add a debugger statement to the application as I have below in the loginBtn click event handler.

When this statement is reached, your application will be paused and the debug tools will automatically be activated. Noticed how the application is greyed out to signify that it has been stopped. Notice also how the Sources tab in the Chrom Dev Tools has popped up open proudly.

Let’s breakdown what we’re seeing.

Source Code

The first thing you might notice is what appears to be a copy of your code. This is the code that the browser has loaded and is running as your application. You can also see that the debugger line is higlighted a blue color to let us know that this is where our application has been paused.

Chrome gives you the ability to view this code for a reason. With the code in front of you, you can now set breakpoints. A breakpoint is intentional stopping or pausing place in a program. The debugger statement we used above functions as a breakpoint, but isn’t necessarily picked up by Chrome as one.

Breakpoint – intentional stopping or pausing place in a program

To add a breakpoint, click in the gutter, or empty space, to the left of the line numbers. As your do, notice that Chrome now adds this breakpoint to the list of breakpoints further down.

Scope

In the scope tab, you have the ability to inspect variables in your application. You’ll notice there is a local section (local scope to the function where the breakpoint is), a global section (the global scope), and a scripts section. In the scripts section, you can view variables within the scope of the current script.

This is where a significant amount of your debugging time will be spent. This is a much more efficient replacement for writing out many console.log() statements.

Watch

As I mentioned earlier, in addition to viewing variables in the scope tab, you can also define variables that you want to look into specifically. By adding a variable to the watch tab, each time you hit a breakpoint, you can quickly find the value of that variable (which may be undefined depending on where you are in the code). Hit the add icon and enter the name of the variable you want to watch to track, in this case, usernameInput.

Step Functions, Call Stack, and Breakpoints List

The last section, located in the bottom left of the Sources tab in my configuration, will allow you to view the list of breakpoints, call stack, etc.

In the call stack above, there is one function listed which is the event handler for my login button. This function is listed because it is the only function that has been called so far. As functions call more functions, that chain will be updated appropriately.

Notice also the arrow buttons at the top of this screenshot. These correspond to the functions referenced above for continuing execution of your code or stepping through it line by line or by function. I would recommend testing these buttons for a bit to get used to how you navigate the execution of your code.

Lastly, there are different kinds of breakpoints that can be set. Let’s take a look at creating a conditional breakpoint, one that will only get triggered if a certain condition is met. For example, let’s say we want to break on the login button callback only when the user attempted to login without entering a username. We can do this, by right-clicking in the gutter and choosing conditional breakpoint with the following condition, usernameInput.text === ''.

In the case of debugging Quick Chat, if you press the login button without entering a username, this breakpoint will be triggered. Otherwise code will continue to execute as normal.

Note that there are even more breakpoint options available that are not covered here.

Debugging in VS Code

The Chrome Developer Tools are some of the best in the business. As you’ve seen so far, they offer a great experience to debug your application with lots of functionality. However, Visual Studio Code has worked really hard to match that debugging functionality in a more seamless way. In my mind, I absolutely love VS Code and want to spend as much time there, and not in other tools, as possible. This includes debugging.

I absolutely love VS Code and want to spend as much time there, and not in other tools, as possible. This includes debugging.

To get started debugging in VS Code, you will need to install the Debugger for Chrome extension.

Let’s take a quick look at the Debug tab in the sidebar (on the left side of your editor by default). Open the debug tab by clicking on the icon that… well looks like a bug. With this pane open, you should recognize very similar tools to what we saw in Chrome… variables, watch, call stack, and breakpoints.

The majority of the functionality that you get in Chrome Dev Tools is available right here inside of VS Code.

Now that we’ve seen the Debug tab, we need to create a launch configuration that tells VS Code how to debug your application. VS Code stores debug configurations in a file called launch.json inside of a folder .vscode. To have VS Code create this file for us, click on the ‘No Configurations’ dropdown and choose ‘Add Configuration’.

VS Code stores debug configurations in a file called launch.json inside of a folder .vscode.

Then choose ‘Chrome’ in this case.

Then, choose the ‘Chrome: Launch’ configuration from the popup dropdown list.

The specific configuration that we created will automatically attach to the application at the defined port. We need to make one small change to this configuration to correctly point to the source code for the app. The source code is located in the public directory, which is why I have updated the ‘webRoot’ property.

**Keep in mind that your application must already be running locally at a certain port for this to work.

With the configuration defined, you can now start your debug session by clicking the green play button. Your application should pop up in a Chrome window as shown. Also, notice the debug menu bar that popped up in the background inside of VS Code. With this debug toolbar, you can pause, restart, continue, and use step functions to navigate your code and interact with the debugger.

With this debug toolbar, you can pause, restart, continue, and use step functions to navigate your code and interact with the debugger.

With debugging connected, you can set a breakpoint in the code, just like we did in Chrome. Click in the ‘gutter’ next to the line number. I’m keeping my breakpoint in the same location as before, just inside the login event callback.

Now, when trying to login without entering a username, the breakpoint should trigger swiching the contect back to VS Code for further investigation.

From here, the functionality that we discussed in Chrome maps over directly to VS Code. If you want to add a conditional breakpoint, right-click in the gutter and choose ‘conditional breakpoint’ with some condition. If you want to watch a variable, click to add a new one, and type the name of the variable to watch. If you want to explore variables, go to the variables tab and explore away!

Recap

As I said ealier, to take that next step as a developer means more than just writing better code. It means taking advantage of the ecosystem of tools that your language lives in. Debugging is one of those topics that takes some time and effort to get started with, but ultimately, the benefit will vastly outweigh the cost.

My recommendation is to spend some time debugging with both Chrome and VS Code, and see what you like best. If you have any questions or comments, find me on twitter, @jamesqquick.

Source:: scotch.io