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.

Categories
Node.js Tips

Node.js Tips — Request URLs, Parsing Request Bodies, Upload

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.

Get Path from the Request

We can get the path from the request by using the request.url to get parse the request URL.

For instance, we can write:

const http = require("http");
const url = require("url");

const onRequest = (request, response) => {
  const pathname = url.parse(request.url).pathname;
  console.log(pathname);
  response.writeHead(200, { "Content-Type": "text/plain" });
  response.write("hello");
  response.end();
}

http.createServer(onRequest).listen(8888);

All we have to do is to get the request.url property to get the URL.

Then we can parse it with the url module.

We can then get the pathname to get the relative path.

Convert Relative Path to Absolute

We can convert a relative path to an absolute path by using the path module’s resolve method.

For example, we can write:

const resolve = require('path').resolve
const absPath = resolve('../../foo/bar.txt');

We call resolve with a relative path to return the absolute path of the file.

Get the String Length in Bytes

We can get the string length in bytes by using the Buffer.byteLength method.

For instance, we can write;

const byteLength = Buffer.byteLength(string, 'utf8');

We pass in a string to Buffer.byteLength to get the string length in bytes.

Get Data Passed from a Form in Express

To get data passed in from a form in Express, we can use the body-parser package to do that.

Then to get the parsed results, we can get it from the req.body property.

We can write:

const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/game', (req, res) => {
  res.render('game', { ...req.body });
});

We call app.post to create a POST route, which gets the request body via req.body because we called bodyParser.urlencoded to parse URL encoded payloads.

extended set to true lets the body-parser accept JSON like data within the form data including nested objects.

With this option, we don’t have to send key-value pairs as we do with traditional HTML form send.

Running Multiple Express Apps on the Same Port

We can use app.use to incorporate multiple Express apps and run them on the same port.

For instance, we can write:

app
  .use('/app1', require('./app1').app)
  .use('/app2', require('./app2').app)
  .listen(8080);

We require app1 and app2 to use the routes from both of them in one app.

Then we call listen to listen to requests in port 8080.

Change Working Directory with NodeJs child_process

We can change the working directory with the cwd option.

For example, we can write:

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

exec('pwd', {
  cwd: '/foo/bar/baz'
}, (error, stdout, stderr) => {
  // work with result
});

We call exec with an object with the cwd property to set the current working directory.

Then we get the result in the callback.

Upload a Binary File to S3 using AWS SDK for Node.js

We can upload a binary file to S3 using the Node.js AWS SDK by using the AWS package.

For instance, we can write:

const AWS = require('aws-sdk');
const fs = require('fs');

AWS.config.update({ accessKeyId: 'key', secretAccessKey: 'secret' });

const fileStream = fs.createReadStream('zipped.tgz');

fileStream.on('error', (err) => {
  if (err) {
    console.log(err);
  }
});

fileStream.on('open', () => {
  const s3 = new AWS.S3();
  s3.putObject({
    Bucket: 'bucket',
    Key: 'zipped.tgz',
    Body: fileStream
  }, (err) => {
    if (err) {
     throw err;
    }
  });
});

We use the aws-sdk package.

First, we authenticate with AWS.config.update .

Then we create a read stream from the file with createReadStream .

Then we listen to the file being opened with by attaching a listener to the 'open' event.

We then create an AWS.S3 instance.

And we call putObject to upload the file.

Bucket is the bucket name.

Key is the path to the file.

Body is the read stream of the file we created.

We also listen to the error event in case any errors are encountered.

Conclusion

We can get the path of the request with the request.url property if we’re using the http module to listen to requests.

To convert relative to absolute paths, we can use the path module’s resolve method.

We can upload files with S3 by creating a read stream and call putObject .

We can set the current working directory with exec .