Categories
Node.js Tips

Node.js Tips — Auto-Scrolling, Delays, Hashing, and Get the Latest Mongo Document

Spread the love

Like any kind of apps, there are difficult issues to solve when we write Node apps.

In this article, we’ll look at some solutions to common problems when writing Node apps.

Using Q delay in Node.js

The Q promise library has a delay method that can delay the execution of code asynchronously.

For instance, we can use it by wiring:

const Q = require('q');

const asyncDelay = (ms) => {
  return Q.delay(ms);
}

asyncDelay(1000)
.then(() => {
  //...
});

We have the asyncDelay function which returns the Q.delay(ms) promise.

It returns a promise that delays the execution of something by the given number of milliseconds.

We can call it and then call then and run the code we want after asyncDelay is done in the then callback.

Also, we can pass in a 2nd argument which can be called a resolved value.

For instance, we can write:

const Q = require('q');

Q.delay(1000, "Success")
  .then((value) => {
      console.log(value);
  });

Then value would be 'Success' since that’s what we passed in as the 2nd argument of delay .

Convert an Image to a base64-Encoded Data URL

To convert an image to a base64-encoded data URL, we can use the readFileSync method to read the file’s data.

Then we pass the content into the Buffer constructor.

And then we can call toString to convert it to a base64 string.

For instance, we can write:

const fs = require('fs');

const file = 'img.jpg';
const bitmap = fs.readFileSync(file);
const dataUrl = new Buffer(bitmap).toString('base64');

We pass the file path into readFileSync .

Then we pass the returned content into the Buffer constructor.

Then we call toString with 'base64' to convert it to a base64 string.

Return the Updated Document with MongoDB findOneAndUpdate

We should set the returnOriginal property to false in the options object to return the updated document in the callback.

For instance, we can write:

db.collection('user_setting').findOneAndUpdate({
  user_id: data.userId
}, {
  $set: data
}, {
  returnOriginal: false
}, (err, res) => {
  if (err) {
    return console.log(err);
  } else {
    console.log(res);
  }
});

The first argument is the query to find the object to update.

The 2nd argument is the data to update the object with.

The 3rd is the options for updating.

We have the returnOriginal option set to false in the 3rd argument.

The last argument is the callback.

res should have the updated results.

Use jQuery Installed with NPM in Express App

To use jQuery installed with NPM in an Express app, we can serve the jQuery’s dist folder with express.static .

For instance, we can write:

const path = require('path');

app.use('/jquery', express.static(path.join(__dirname,  '/node_modules/jquery/dist/')));

Then we can use it in our HTML file by writing:

<script src="/jquery/jquery.js"></script>

Scroll Down Until We Can’t Scroll with Puppeteer

We can check if we’re at the end of the page and use the scrollBy method to scroll.

For instance, we can write:

const distance = 100;
const delay = 100;
while (document.scrollingElement.scrollTop + window.innerHeight < document.scrollingElement.scrollHeight) {
  document.scrollingElement.scrollBy(0, distance);
  await new Promise(resolve => { setTimeout(resolve, delay); });
}

We check if we’re can scroll with:

document.scrollingElement.scrollTop + window.innerHeight < document.scrollingElement.scrollHeight

When scrollTop and innerHeight is less than scrollHeight , we can scroll.

Find OS Username in Node.js

We can get the current user’s username with the os module.

We write:

require("os").userInfo().username

to get the username

In Windows 10, it returns the first name of the owner account that has been used.

There’s also the username module.

We can install it by running:

npm install username

Then we can use it by writing:

const username = require('username');

(async () => {
  console.log(await username());
})();

Hash JavaScript Objects

To hash JavaScript objects, we can use the object-hash module.

For instance, we can write:

const hash = require('object-hash');

const obj = {a: 1, b: 2};
const hashed = hash(obj);

We just call the hash function from the package to return a hashed string.

Conclusion

We can hash JavaScript objects with the object-hash module.

Also, we can get the username with os or a 3rd party module.

The Q promise library has a delay method to delay execution of functions.

We can get the updated object with findOneAndUpdate .

We can scroll until we can’t scroll with Puppeteer by checking the heights.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *