Categories
Node.js Tips

Node.js Tips —MongoDB Connections, Fetch, and Exports

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.

Retrieve Data from a ReadableStream Object Returned From the Fetch API

We can retrieve data from a ReadableStream object by calling conversion functions to convert it to the data type we want.

For instance, we write:

fetch('https://api.agify.io/?name=michael')
  .then(response => response.json())
  .then((data) => {
    console.log(data);
  });

We did the conversion to JSON with the response.json() call.

Then we can get the data in the next then callback.

Share Variables Between Files in Node.js

We can share variables by creating modules.

For instance, we can write:

module.js

const name = "foo";
exports.name = name;

app.js

const module = require('./module');
const name = module.name;

We export the name constant by setting it as a property of exports .

Then we import it with require in app.js .

And we can use it like any other property.

Using fs in Node.js with async / await

We can use async and await with fs methods if we convert them to promises first.

For instance, we can write:

const fs = require('fs');
const util = require('util');

const readdir = util.promisify(fs.readdir);

const read = async () => {
  try {
    const names = await readdir('/foo/bar/dir');
    console.log(names);
  } catch (err) {
    console.log(err);
  }
}

We convert the fs.readdir method, which reads a directory, to a promise version with util.promisify .

Then we can use it with async and await .

Mongoose and Multiple Database in Single Node.js Project

We can connect to multiple MongoDB databases in a single Node project.

For instance, we can write:

fooDbConnect.js

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/foo');
module.exports = exports = mongoose;

bazDbConnect.js

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/baz');
module.exports = exports = mongoose;

We connect to different databases with connect in each file and export the connections.

Then in db.js , we write:

const mongoose = require("./`fooDbConnect`");

to connect to the foo database.

Use of module.exports as a Constructor

We can export a constructor with module.exports .

For example, we can write:

person.js

function Person(name) {
  this.name= name;
}

Person.prototype.greet = function() {
  console.log(this.name);
};

module.exports = Person;

Then we can import it by writing:

app.js

const Person = require("./`person`");
const person = new Person("james");

We import the Person constructor in app.js and then invoked it in the last line.

Read a Text File Using Node.js

We can read a text file with the fs.readFile method.

For instance, we can write:

const fs = require('fs');

fs.readFile('./foo.txt', 'utf8', (err, data) => {
  if (err) {
    console.log(err);
  }
  console.log(data);
});

We pass in the file path as the first argument.

The encoding is the 2nd argument.

The callback that’s called when the file read operation is done is the 3rd argument.

data has the file and err has the error object is an error is encountered.

Reuse Connection to MongoDB Across Node Modules

We can export the MongoDB connection so that we can use them in other Node app modules.

For example, we can write:

dbConnection.js

const MongoClient = require( 'mongodb' ).MongoClient;
const url = "mongodb://localhost:27017";

let _db;

module.exports = {
  connect(callback) {
    MongoClient.connect( url, { useNewUrlParser: true }, (err, client) => {
      _db  = client.db('some_db');
      return callback(err, client);
    });
  },

  getDb() {
    return _db;
  }
};

We created the connect function to connect to the MongoDB database.

The connection object is set to a variable.

It takes a callback that we can use to get any errors is there is any.

Then we created the getDb function to get the MongoDB connection.

Then we can use connect.js by writing:

const dbConnection = require('dbConnection');

dbConnection.connect((err, client) => {
  if (err) {
    console.log(err);
  }
} );

We connect to the database in our file by importing the dbConnection module we created earlier.

Then we call connect with the callback we want.

We called it with err and client in dbConnection.js so that’s what we have as the parameter of the callback.

Conclusion

MongoDB connections can be shared between modules.

We’ve to convert the raw response from the fetch function to the data type we want before we can use the data.

fs methods can be converted to promises.

We can export constructors with module.exports.

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 *