Categories
Node.js Tips

Node.js Tips — Async and Map, Async and MongoDB, and Copying Files with S3

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.

Call an Async Function within map

We can use Promise.all to map functions to async functions.

For instance, we can write:

const asyncMap = async (teachers) => {
  const data = await Promise.all(teachers.map(async teacher => {
    return {
      ...teacher,
      image: `${teacher.name}.jpg`
   }
  }));
  //...
}

We map the teachers array to an array of promises with map .

An async function returns a promise, so we can just add the async keyword in front of the callback for map .

Then we can use await and Promise.all to invoke all the promises in parallel.

And we can do whatever we want with the results afterward.

Watch Directory for Changes with Nodemon

We can use the --watch option to watch multiple files and directories.

For example, we can run:

nodemon --watch src app.js

to watch the src folder and app.js .

Copy All Objects in Amazon S3 from One prefix to Another Using the AWS SDK for Node.js

To copy objects from one key to another, we can use the listObjects to list the entries.

Then we can use copyObject to copy the entries to the key location.

For example, we can write:

const AWS = require('aws-sdk');
const async = require('async');
const bucketName = 'foo';
const oldPrefix = 'bar/';
const newPrefix = 'baz/';
const s3 = new AWS.S3({ params: { Bucket: bucketName }, region: 'us-west-2' });

const done = (err, data) => {
  if (err) { console.log(err); }
  else { console.log(data); }
};

s3.listObjects({ Prefix: oldPrefix }, (err, data) => {
  if (data.Contents.length) {
    async.each(data.Contents, (file, cb) => {
      const params = {
        Bucket: bucketName,
        CopySource: `${bucketName}/${file.Key}`,
        Key: file.Key.replace(oldPrefix, newPrefix)
      };
      s3.copyObject(params, (copyErr, copyData) => {
        if (copyErr) {
          console.log(copyErr);
        }
        else {
          console.log(params.Key);
          cb();
        }
      });
    }, done);
  }
});

We call listObjects with the oldPrefix to get the items in the lol path.

The entries are stored in data.Contents .

Then we use async.each to iterate through each object.

Bucket has the bucket name.

CopySource has the original path.

Key has the new key, which we call replace to with the oldPrefix and newPrefix to replace it with the oldPrefix with newPrefix .

We pass the params object to the copyObject method.

Then we get the results afterward.

Once we did that, we call cb to complete the iteration.

We call done which we defined earlier to print any errors or results.

Sequential MongoDB Query in Node.js

We can use async and await to make MongoDB queries in a synchronous style.

It looks synchronous in that it’s sequential, but it’s asynchronous.

For instance, we can write:

const getPerson = async () => {
  const db = await mongodb.MongoClient.connect('mongodb://server/db');
  if (await db.authenticate("username", "password")) {
    const person = await db.collection("Person").findOne({ name: "james" });
    await db.close();
    return person;
  }
}

return returns a promise that resolves to person .

It doesn’t actually return person .

db.collection gets the collection we want to query.

findOne finds one entry that matches the condition in the object.

We look for an entry with name value 'james' .

The resolved value of the query is set to person .

Then we call db.close when we’re done the query.

Then we return person to resolve the returned promise to that value.

Automatically Add the Header to Every “render” Response in an Express App

We can make our own middleware to add a header to every response.

For instance, we can write:

app.use((req, res, next) => {
  res.header('foo', 'bar');
  next();
});

With res.header , we add the 'foo' response header with value 'bar' to all responses.

Then we call next to run the next middleware.

This piece of code should be added before the routes so that it runs before each route.

Conclusion

We can call map to map each entry to a promise.

Then we call Promise.all to invoke them in parallel.

We can use the AWS SDK to copy files in S3.

MongoDB methods support promises.

We can add response headers to all routes with a middleware.

Categories
Node.js Tips

Node.js Tips — MongoDB and SQL

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.

MongoDB Driver async/await Queries

The MongoDB Node drive supports promises, so we can use async and await in our queries.

For instance, we can write:

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

(async () => {
  const client = await MongoClient.connect(
    connectionString, {
      useNewUrlParser: true
    }
  );
  const db = client.db('dbName');
  try {
    const res = await db.collection("collectionName")
      .updateOne({
        "foo": "bar"
      }, {
        $set: {}
      }, {
        upsert: true
      });
    console.log(res);
  } finally {
    client.close();
  }
})()

We call MongoClient.connect with the connectionString .

Then we get the database to manipulate with client.db .

We then use the db.collection method to get the collection to query.

Then we call updateOne to update the entry with the given field with the value.

Pressing Enter Button in Puppeteer

We can press the Enter button with Puppeteer by writing:

await page.type(String.fromCharCode(13));

13 is the key code for the Enter key.

Also, we can use the press method on an element.

For example, we can write:

await (await page.$('input[type="text"]')).press('Enter');

We select an input with type text and call press with 'Enter' as the argument.

'\n' and '\r' are also alternatives for 'Enter' , so we can write:

await page.keyboard.press('n');

or:

await page.keyboard.press('r');

To press the Numpad Enter key, we can write:

await (await page.$('input[type="text"]')).press('NumpadEnter');

We select the input with type text and call press with 'NumpadEnter' .

There’s also the sendCharacter method:

await page.keyboard.sendCharacter(String.fromCharCode(13));

Check for undefined Property in EJS for Node.js

We can use the typeof operator to check for an undefined property.

For instance, we can write:

const template = '<% (typeof foo !== "undefined" ? %>foo defined<% : %>foo undefined<% ) %>';

We just use the typeof operator just like in JavaScript.

Then we show foo defined if it’s defined.

Otherwise, we show foo undefined .

Listen to All Interfaces Instead of Localhost Only with Express

We can specify the IP address with app.listen to listen to.

To listen to all address, we can pass in '0.0.0.0' .

For example, we can write:

const express = require('express');
const app = express();

//...
app.listen(3000, '0.0.0.0');

How to Find the Size of the File in Node.js

To find the size of a file, we can use the statSync method.

For instance, we can write:

const fs = require("fs");
const stats = fs.statSync("foo.txt");
const fileSizeInBytes = stats.size;

We call statSync with the file path to get data about the file.

Then we use the size property to get the file size in bytes.

List Available Crypto Algorithms

We can use the crypto module to get the list of algorithms.

To get them, we use the getCiphers to get available ciphers.

And we can also use getHashes to get the available hashes.

So we can write:

const crypto = require('crypto');
console.log(crypto.getCiphers());
console.log(crypto.getHashes());

Set _id to DB Document with Mongoose

To let us set the _id of the database document with Mongoose, we can put the _id property in the Schema.

Or we can ser the _id option to false .

For instance, we can write:

const Person = new mongoose.Schema({
  _id: Number,
  name: String
});

or:

const Person = new mongoose.Schema({
  name: String
}, { _id: false });

All a Where Clause Conditionally to a Knex Query

To add a where clause conditionally to a Knex query, we can store the general query in a variable.

Then we can write:

const query = knex('persons')
  .select('name', 'james')
  .limit(50);

if (age) {
  query.where('age', age);
}

We add the where clause for age only if age is defined.

Or, we can use the modify method.

For instance, we can write:

knex('persons')
  .select('name', 'james')
  .limit(50);
  .modify((queryBuilder) => {
    if (age) {
      queryBuilder.where('age', age);
    }
  });

We make our age query in the callback instead of storing the query in a variable.

Conclusion

The MongoDB Node driver supports promises.

We can press Enter with Puppeteer in many ways.

We can make Knex queries conditionally.

Also, we can listen to all IP addresses with Express apps.

_id can be set if we specify it in the Mongoose schema.

Categories
Node.js Tips

Node.js Tips — Read JSON, Serve Static Files, Sorting File Listings

As with any kind of app, 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.

Route All Requests to index.html with Express

We can route all requests to index.html in an Express app by using the * wildcard to listen to all requests.

For instance, we can write:

const express = require('express');
const path= require('path');
const server = express();

server.use('/public', express.static(path.join(__dirname, '/assets')))

server.get('/hello', (req, res) => {
  res.send('hello');
})

server.get('/*', (req, res) => {
  res.sendFile(path.join(__dirname + '/index.html'));
})

const port = 8000;
server.listen(port);

We have an Express app that serves the /assets folder with the /public route. Then we define a GET route that’s not a catch-all route to listen to GET requests with that path. Then we define our catch-all route to render index.html . Anything that doesn’t match /public or /hello rendersindex.html .

Re-throwing Exception and not Losing Stack Trace

We can rethrow an exception and not lose the stack trace by rethrowing the error object in the catch clause.

For instance, we can write:

try {
  //...
  throw new Error("error");
  //...
} catch(err) {
  err.message = `error: ${err.message}`;
  throw err;
}

We run something that throws an error in the try block.

Then in the catch block, we change the err.message as we want to and keep the stack trace.

Then we throw the err object again after it’s modified.

Read JSON File Content with require vs fs.readFile

require reads the JSON file content synchronously.

The file is parsed without any extra work.

For instance, if we have:

const obj = require('./someJson');

then we read the someJson.json file and assign the returned value to obj .

We don’t need the .json extension and it’s parsed without any code.

If we use readFile , then we read the JSON file asynchronously.

Also, we’ve to parse the text with JSON.parse to convert it to an object.

For example, we can write:

const fs = require('fs');

fs.readFile('/path/test.json', 'utf8', (err, data) => {
  if (err) {
    return console.error(err);
  }
  const obj = JSON.parse(data);
});

We pass in the path as the first argument.

The encoding is the 2nd argument.

The callback is the 3rd argument.

data has the data, which is in a string.

We used JSON.parse to parse into an object.

We can also do the same thing synchronously with readFileSync .

For instance, we can write:

const fs = require('fs');
const json = JSON.parse(fs.readFileSync('/path/test.json', 'utf8'));

We pass in the path and encoding and it’ll return the JSON string.

Then we call JSON.parse to parse the string.

We can use require to cache the object.

readFileSync is faster out of the 3 choices according to https://github.com/jehy/node-fastest-json-read/runs/416637981?check_suite_focus=true

readFile is the slowest but doesn’t block the event loop.

Basic Web Server with Node.js and Express for Serving HTML File and Assets

We can use the connect package to make a basic web serve to serve static files.

To install it, we run:

npm install connect

Then in our code file, we can write:

const connect = require('connect');
const port = 1234;

connect.createServer(connect.static(__dirname)).listen(port);

We call createServer to create the webserver.

connect.static is a middleware to let us serve the static files.

listen selects the port that we listen to requests from.

With Express, we can write:

const express = require('express');
const app = express();
const http = require('http');
const path = require('path');
const httpServer = http.Server(app);

app.use(express.static(path.join(__dirname, '/assets')));

app.get('/', (req, res) => {
  res.sendfile(path.join(__dirname, '/index.html'));
});
app.listen(3000);

We use the express.static middleware to serve static files.

Then we can access them from index.html , where we access the assets folder.

Get a List of Files in Chronological Order

We can sort a list of files that are returned from readdirSync by using the sort method.

For instance, we can write:

const fs = require('fs');
const path = require('path');
const dir = './';
const files = fs.readdirSync(dir);
files.sort((a, b) => {
  return fs.statSync(path.join(dir, a)).mtime.getTime() -   fs.statSync(path.join(dir, b).mtime.getTime();
});

In the sort callback, we use getTime to get the timestamp of when the files are modified.

We subtract them to sort in ascending order.

We can do the same thing with readFile in the callback.

Conclusion

We can serve static files and route requests to static pages. Files can be sorted once they’re read. Error objects can be modified and rethrown. JSON can be read with various methods.

Categories
Node.js Tips

Node.js Tips — Build Errors, Tests, and Exit Codes

As with any kind of app, 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.

Fix NPM Error on Windows Looking for Tools Version

If we install native Node packages on Windows, we may run into errors that look something like:

MSBUILD : error MSB4132: The tools version "2.0" is unrecognized. Available tools versions are "4.0".

To fix this, we can run:

npm install --global --production windows-build-tools

in admin mode to install the build tools for Windows to compile those packages.

Use a Custom Express Server in Supertest

We have to export out Express server so that it can be tested with Supertest.

For instance, we can write:

app.js

//...
const app = express();
//...

module.exports = app;

Then in our test, we can write:

const request = require('supertest');
const app = require('./app');

describe('POST /', () => {
  it('should make request with foo', (done) => {
    request(app)
      .post('/')
      .send({
        'foo': 'bar'
      })
      .expect(200)
      .end((err, res) => {
        console.dir(err);
        console.dir(res);
        //...
        done();
      })
  })
})

We pass in the app which exported into the request function to make a request with our Express app.

Get Query String Params with Koa Router

To get a query string parameter with the Koa router, we can use the ctx.request.query property.

For instance, we can write:

import koaRouter from 'koa-router';

const router = koaRouter({
  prefix: '/foo'
});

router.get('/', async (ctx) => {
  console.log(ctx.request.query);
});

to get the parsed query parameters.

We can also use ctx.query for short:

import koaRouter from 'koa-router';

const router = koaRouter({
  prefix: '/foo'
});

router.get('/', async (ctx) => {
  console.log(ctx.query);
});

Accessing the Exit Code and stderr of a System Command

We can access the exit code and stderr of a system command by getting them from the error object.

For instance, if we’re using execSync to run our command, then we can write:

const childProcess = require('child_process');
const cmd = 'some command';

try {
  childProcess.execSync(cmd).toString();
} catch (error) {
  console.log(error.status);
  console.log(error.message);
  console.log(error.stderr);
  console.log(error.stdout);
}

We call execSync with a command.

Then we get the error with the catch block.

status has the exit code.

message has error messages.

stderr has the full error output.

stdout has the standard output.

If we use exec , we can get the error from the callback.

const childProcess = require('child_process');
const cmd = 'some command';

child_process.exec(cmd, (err, stdout, stderr) => {
  console.log(stdout)
  console.log(stderr)
  console.log(err)
}).on('exit', code => console.log(code))

We can get the stdout and stderr from the callback.

The exit code can be obtained by listening to the exit event.

It takes a callback with the exit code, which is the value of code .

err has the errors encountered.

Node.js server.address().address Returns :: in an Express App

To make server.address return an IP address, we’ve to specify the IP address specifically with listen .

For example, we can write:

const express = require('express');
const app = express();
const server = app.listen(8888, "127.0.0.1", () => {
  const { address, port } = server.address();
  console.log(`running at http://${host}:${port}`);
});

We pass in the IP address as the 2nd argument.

Then server.address will get the host , which has the IP address, and port , which has the port.

Unit Test an Event Being Emitted in Mocha

We can listen to events in our Mocha tests.

For instance, we can write:

it('should emit an event', function(done){
  this.timeout(1000);

  eventObj.on('event', () => {
    // run assertions...
    done();
  });
});

We call this.timeout to make sure that the test times out with an error if the event isn’t received in 1 second.

Then we can listen to the event event emitted by eventObj and run any assertions we want with it.

After that, we call done to move on to other pieces of code.

Conclusion

We can pass the IP address on listen to get the IP address the app is listening to with server.address() . Errors and exit code for shell commands can be retrieved with exec and execSync . We’ve to install windows-build-tools globally to fix any errors with build native packages. To test our Express app with Supertest, we’ve to import our Express app object and pass it to Supertest’s request function before we make our request.

Categories
Node.js Tips

Node.js Tips — Babel, Promises, Latest/Oldest MongoDB Records

As with any kind of app, 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.

Get the Latest and Oldest Record in Mongoose

We can get the latest document by using the sort method.

For instance, we can write:

MySchema.find().sort({ _id: -1 }).limit(1)

to get the latest document.

_id set to -1 means we sort the IDs in descending order.

To get the oldest document, we can write:

MySchema.find().sort({ _id: 1 }).limit(1)

_id set to 1 means we sort the IDs in ascending order.

limit limits the entries returned.

Add 1 Month from Now to Current Date in moment.js

We can add 1 month from now with monent.js with the add method.

For instance, we can write:

moment().add(1, 'months').calendar();

moment returns the current date and time.

We just call add with the quantity and the unit that we want to add to add what we want to the date.

Also, we can replace 'months' with 'days' and 'years' to add those quantities as well.

Convert Native Promise to a Bluebird

We can call Blurbird’s resolve method to convert a native promise to a Bluebird promise.

For example, we can write:

Promise.resolve(somePromise())

where somePromise is a function that returns a native ES6 promise.

Get “HTTP_REFERER” with NodeJS

If we use the http module to create our HTTP server, we can use the req.headers.referer to get the HTTP_REFERER header from the request.

For instance, we can write:

const http = require('http');
const server = http.createServer((req, res) => {
  console.log(req.headers.referer);
})

JavaScript Asynchronous Constructor

We can create static async methods in JavaScript classes, so we can use that to create methods that returns a promise with a resolved value we want.

For instance, we can write:

class Person{
  constructor(name){
    this.age = 5;
    this.name = name;
    return new Promise((resolve) => {
      resolve(this);
    });
  };
}

We have the Person constructor which returns a promise.

If we return something in the constructor , then it’ll be returned instead of returning the instance directly.

We returned a promise that resolves to the Person instance, so we can call then to get the resolved result.

Then we can call then on it by writing:

new Person('james')
  .then((instance) => {
    //...
  });

instance has the Person instance, and we can do what we like with it.

Using Babel Register with require(‘babel/register’)

To use Babel in our app without any transportation, we can use the babel/register package.

We add the package on top of our script, then we can use the features supported by the preset.

To use it, we run:

npm install @babel/core @babel/register --save-dev

to install @babel/core and @babel/register to add Babel Register.

Then to use it, we can write:

require("@babel/register");

const env = process.env.NODE_ENV || 'development';
const port = process.env.NODE_PORT || 8888;

const http = require('http');
const express = require('express');

const app = express();

app.set('port', port);
app.use(express.static(path.join(__dirname, 'public')));

app.get('*', (req, res) => {
  res.send('hello!');
});

http.createServer(app).listen(app.get('port'), () => {
  console.info('app started');
});

We require the babel-register package at the top of the script.

Then we run our Express apps with the latest features below it.

Now the Express app is transpiled on the fly.

Also, we can add babel-cli to our project instead of using Babel Register, which is faster since it doesn’t do on-the-fly transpilation.

To do that, we can run:

npm install --save-dev @babel/core @babel/node

to install the Babel packages.

Then we can run babel-node in our app:

npx babel-node app.js

Then we can write:

app.js

const env = process.env.NODE_ENV || 'development';
const port = process.env.NODE_PORT || 8888;

const http = require('http');
const express = require('express');

const app = express();
app.set('port', port);

app.use(express.static(path.join(__dirname, 'public')));

app.get('*', (req, res) => {
  res.send('hello!');
});

http.createServer(app).listen(app.get('port'), () => {
  console.info('app started');
});

and it’ll run properly since we’re using Babel to transpile the app.

Conclusion

We can get the oldest and latest records with Mongoose easily. Also, we can use Babel Register or Babel Node to run our app. We can return anything in our constructor including promises, so we can use that to create an async constructor. We can get the HTTP referer from the headers. Native promises can be converted to Bluebird promises.