Categories
Node.js Tips

Node.js Tips — Format JSON, Remove Object with MongoDB, Parallel Execution

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.

Write Formatted JSON in Node.js

To print formatted JSON in Node apps, we can use the JSON.stringify method with some extra arguments.

For instance, we can write:

JSON.stringify(obj, null, 2)

to add 2 spaces for indentation.

Remove Object from Array with MongoDB

We can remove an object from an array with MongoDB by using the update method.

For instance, we can write:

db.collection.update(
  {'_id': ObjectId("5150a1199fac0e6910000002")},
  { $pull: { "items" : { id: 123 } } },
  false,
  true
);

We pass in the query, which is the ID of the document that has the array.

Then 2nd argument gets the item to update, which is what we want to remove from the items array.

$pull removes the item in the array.

The 3rd argument means we don’t want to do upsert.

The last argument means we process multiple documents.

console.log vs console.info in Node.js

We use the console.log method to log general messages.

console.info is specifically used for logging informational messages.

However, they pretty much do the same thing other than the name and their intended use.

Copy to Clipboard in Node.js

To copy something to the clipboard, we can run a shell command to copy something to the clipboard.

For instance, in Linux, we can write:

const exec = require('child_process').exec;

const getClipboard = (func) => {
  exec('/usr/bin/xclip -o -selection clipboard', (err, stdout, stderr) => {
    if (err || stderr) {
      throw new Error(stderr);
    }
    func(null, stdout);
  });
};

getClipboard((err, text) => {
  if (err) {
    console.error(err);
  }
  console.log(text);
});

We get the clipboard’s content and output it to standard out with the command.

Also, we can use the clipboardy package to read and write from the clipboard.

For instance, we can write:

const clipboardy = require('clipboardy');
clipboardy.writeSync('copy me');

to copy to the clipboard.

To paste from the clipboard, we can write:

const clipboardy = require('clipboardy');
`clipboardy.readSync();`

Coordinating Parallel Execution in Node.js

To coordinate parallel execution of code in a Noe app, we can use the async library.

For instance, we can write:

const async = require('async');
const fs = require('fs');
const A = (c) => { fs.readFile('file1', c) };
const B = (c) => { fs.readFile('file2', c) };
const C = (result) => {
  // get all files and use them
}

async.parallel([A, B], C);

We have 3 read file processes and we group the first 2 together so that we can run them together in parallel.

Then once they’re both done, we run function C .

Then we have full control of which ones to run in parallel and which one to run in series with the parallel method.

Require and Functions

If we want to call require to import a function.

Then we’ve to assign the function to module.exports .

For instance, if we have:

app/routes.js

module.exports = (app, passport) => {
  // ...
}

Then we can write:

require('./app/routes')(app, passport);

to call import the function and call it immediately.

async/await and ES6 yield with Generators

async and await are very closely related to generators.

They are just generators that always yield promises.

They’re compiled to generators with Babel.

async and await always use yield .

It’s used to unwrap the yielded values as promises and pass the resolved value to the async function.

We should use async and await for chaining promises since we can chain them as if the code is synchronous.

However, it can only return promises.

async and await is an abstraction built on top of generators to make working with them easier.

Get Data Out of a Node.js HTTP Get Request

We can make a GET request with the http module by using its get method.

For instance, we can write:

const http = require('http');

const options = {
  //...
};

http.get(options, (response) => {
  response.setEncoding('utf8')
  response.on('data', console.log)
  response.on('error', console.error)
})

response is a read stream, so we’ve to listen to the data event to get the data.

And we listen to the error event to get the error.

Conclusion

We can use the http module to make GET requests.

To remove an item from an array in a MongoDB document, we can use the update method with the $pull command.

The async module lets us deal with parallel and serial execution of functions.

Also, we can manipulate the clipboard by using shell commands or the 3rd party libraries.

async and await are abstraction on top of generators.

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 *