Categories
Node.js Tips

Node.js Tips — Config Files, Validating Strings, Multiple Streams,

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.

Validation Library for Node.js

To validate data in a Node app, we can use a library to make our lives easier.

For instance, we can use the validator package.

We can use it by writing”

const check = require('validator').check;
const sanitize = require('validator').sanitize;

check('test@email.com').len(6, 64).isEmail();
check('abc').isInt();

const int = sanitize('0123').toInt();
const bool = sanitize('true').toBoolean();

We check is the email is between the length of 6 and 64 with the len method.

Then we called the isEmail method to check if it’s an email.

check checks a string with something validator methods.

sanitize cleans up the string.

isInt checks for integers.

If it’s not valid, then an exception would be thrown.

toInt converts a string to an int.

toBoolean converts a string to a boolean.

Piping the Same Readable Stream into Multiple Writable Targets

We can pipe the same readable stream into multiple writable targets.

For instance, we can write:

const spawn = require('child_process').spawn;
const PassThrough = require('stream').PassThrough;

const a = spawn('ls');
const b = new PassThrough();
const c = new PassThrough();

a.stdout.pipe(b);
a.stdout.pipe(c);

let output = '';

b.on('data', (chunk) => {
  output += chunk.length;
});

b.on('end', () => {
  console.log(count);
  c.pipe(process.stdout);
});

We can pipe the output of the ls shell command that’s run with the spawn method with the PassThrough instances.

We get the stdout property, which is a readable stream, and call pipe on it to pipe it to the writable streams which we created with the PassThrough constructor.

Then we listen to the streams by adding listeners to the data and end methods.

.rc Configuration Files

Anyone can make .rc files to create their own configuration file.

We can make a .rc file that has JSON for example.

For instance, we can write:

const fs = require('fs');
fs.readFile('./.barrc', 'utf8', (err, data) => {
  if (err) {
    return console.error(err);
  }
  console.log(JSON.parse(data));
})

We call readFile to read the file, then we can parse the JSON that’s stored in it.

It can also hold YAML or any other standard text format.

Determine if a String is a MongoDB ObjectID

We can determine if a string is a MongoDB Object ID by using the ObjectId.isValid method.

For example, we can write:

const ObjectId = require('mongoose').Types.ObjectId;
ObjectId.isValid('4738');

It checks if a string is a 12 character long string or if it’s in the correct format.

Perform a Full-Text Search in MongoDB and Mongoose

We can perform a full-text search in MongoDB by creating an index.

Then we can use the find method to search for the field we want.

For example, we can write:

const schema = new Schema({
  name: String,
  email: String,
  address: {
    street: String,
  }
});
schema.index({name: 'text', 'address.street': 'text'});

We can also include all fields in our index by writing:

schema.index({'$**': 'text'});

Then we can call find by writing:

Person.find({ $text: { $search: search }})
  .skip(20)
  .limit(20)
  .exec((err, docs) => {
    //...
  });

Update a Line Rather than Create a New Line with console.log

We can clear the existing lines and then write the new line with the process module.

For instance, we can write:

process.stdout.write("Hello, World");
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write("n");

We called write with some text to display it on the screen.

Then we called clearLine to clear the line.

Then we called cursorTo with 0 to move the cursor back to the left side.

Then we write the end of line character on the screen.

Write Objects into File with Node.js

To write objects into a file in a Node app, we can use writeFileSync to write it.

We can write an array by writing:

fs.writeFileSync('./data.json', arr.join(',') , 'utf-8');

We called join to combine the entries into a string.

Then writeFileSync would write the string to data.json .

To write an object’s content into a file, we can use util.inspect to convert it into a formatted string.

Then we write that to a file.

For example, we can write:

const util = require('util');
fs.writeFileSync('./data.json', util.inspect(obj) , 'utf-8');

Conclusion

We can write an object into a file.

Validation strings are easy if we use a library.

We can pipe readable streams into multiple write streams.

Also, we can make our own .rc configuration files in whatever format we want.

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 *