Categories
Node.js Tips

Node.js Tips — Timestamp, Cookies, Send File Responses and Fetch

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.

Fix ‘ReferenceError: fetch is not defined’ Error

The Fetch API isn’t implemented in Node.

If we want to use it, we can use the node-fetch library.

To install it, we run:

npm i node-fetch --save

Then we can use it by writing:

const fetch = require("node-fetch");

There’s also the cross-fetch library.

We can install it by running:

npm install --save cross-fetch

Then we can write:

import fetch from 'cross-fetch';

fetch('https//example.com')
  .then(res => {
    if (res.status >= 400) {
      throw new Error("error");
    }
  })

Avoid Long Nesting of Asynchronous Functions in Node.js

We can reorganize our nested async functions by rewriting it as multiple functions.

For example, we can write:

http.createServer((req, res) => {
  getSomeData(client, (someData) => {
    getMoreData(client, function(moreData) => {
         //
      });
   });
});

to:

const moreDataParser = (moreData) => {
   // date parsing logic
};

const dataParser = (data) => {
  getMoreData(client, moreDataParser);
};

const callback = (req, res) => {
  getSomeData(client, dataParser);
};

http.createServer(callback);

We move the anonymous functions into their own named functions so we can call them one by one.

Use of the “./bin/www” in Express 4.x

./bin/www is the file with the entry point of the Express app.

In the start script, we have:

"scripts": {
  "start": "node ./bin/www",
}

to start the app.

Get and Set a Single Cookie with Node.js HTTP Server

If we’re using the http module to create a server, we can parse a cookie by splitting the string .

For instance, we can write:

const http = require('http');

const parseCookies = (cookieStr) => {
  const list = {};
  const cookies = cookieStr && cookieStr.split(';');
  for (const cookie of cookies) {
    const [key, value] = cookie.split('=');
    list[key.trim()] = decodeURI(value);
  });
  return list;
}

http.createServer((request, response) => {
  const cookies = parseCookies(request.headers.cookie);
  //...
}).listen(8888);

We get the cookie string with request.headers.cookie .

Then we pass that into the parseCookie function.

It splits the cookie string by the semicolon.

Then we loop through them to split the parts by the = sign.

The left side is the key and the right is the value.

To set a cookie, we can write:

const http = require('http');

`http.createServer((request, response) => {
  ` response.writeHead(200, {
    'Set-Cookie': 'foo=bar',
    'Content-Type': 'text/plain'
  });
  response.end('hellon');`
}).listen(8888);`

We use writeHead to set headers.

'Set-Cookie' sets the response cookie.

'Content-Type' sets the content type of the response.

Then we use response.end to return the response body.

Get Request Path with the Express req Object

We can use the req.originalUrl property to get the request path of the Express req object.

Copy Folder Recursively

We can copy a folder recursively with the node-fs-extra package.

Its copy method lets us do the copying recursively.

For instance, we can write:

fs.copy('/tmp/oldDir', '/tmp/newDir', (err) => {
  if (err) {
    console.error(err);
  } else {
    console.log("success");
  }
});

The argument is the old directory path.

The 2nd is the new directory path.

The last argument is the callback that’s run when the copy operation ends.

err has the error.

Return the Current Timestamp with Moment.js

We can return the current timestamp in Moment.js with a few methods.

We can write:

const timestamp = moment();

or:

const timestamp = moment().format();

or:

const timestamp = moment().unix();

or:

`const timestamp =` moment().valueOf();

to get the timestamp.

We can also convert it to a Date instance and call getTime :

const timestamp = moment().toDate().getTime();

Fix the ‘TypeError: path must be absolute or specify root to res.sendFile’ Error

This error can be fixed if we pass in an absolute path to res.sendFile .

To do that, we write:

res.sendFile('index.html', { root: __dirname });

or:

const path = require('path');
res.sendFile(path.join(__dirname, '/index.html'));

Either way, we get the absolute path which is required by res.sendFile .

Conclusion

We’ve to parse cookies manually if we use http to create our server.

Fetch API isn’t included with Node’s standard library.

res.sendFile only takes an absolute path.

We can rewrite nested callbacks by reorganizing them into their own functions.

Moment returns the current timestamp with a few functions.

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 *