Categories
Express JavaScript Answers

How to Add Response Timeout Feature to an Express.js App?

To add a response timeout feature to an Express.js app to end requests that take too long to process, we can use the connect-timeout package.

To install it, we run:

npm i `connect-timeout`

Then we can use it by writing:

const express = require('express')
const timeout = require('connect-timeout');
const app = express()
const port = 3000
const haltOnTimedout = (req, res, next) => {
  if (!req.timedout) {
    next();
  }
}

app.use(timeout(120000));
app.use(haltOnTimedout);

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

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

We include the module with require .

Then we create the haltOnTimeout function that checks the req.timedout property to see if the request has timed out.

If it hasn’t timed out, then req.timedout is false and we call next to move forward with the request.

This property is available which we added:

app.use(timeout(120000));

to add the connect-timeout middleware to detect the timeout.

120000 is in milliseconds and it’s the number of milliseconds before the request times out.

Categories
Express JavaScript Answers

How to Accept form-data Request Data with Express?

To accept form-data request data in our Express app, we can use the body-parser package.

To install it, we run:

npm i body-parser

Then we can use it by writing:

const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const port = 3000

app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(bodyParser.urlencoded({ extended: true }));

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

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

so that we can accept form-data requests in our Express app.

We call bodyParser.urlencoded to accept form-data requests.

The extended option lets us choose between parsing the URL-encoded data with the querystring library with its set to false or the qs library when it’s set to true .

Therefore, when we make a x-www-form-urlencoded request with some key-value pairs, we should get them in the req.body object.

So we’ll see them returned as the response when we make a POST request to the / route.

Categories
JavaScript Answers Nodejs

How to Convert CSV to JSON in Node.js?

To convert CSV to JSON in our Node.js apps, we can use the csvtojson library.

To install it, we run:

npm i csvtojson

Then we if have the following in sample.csv :

a,b,c,d
1,2,3,4
5,6,7,8

then we can convert the CSV file content into a JSON object by writing:

const csv = require("csvtojson");
const csvFilePath = './sample.csv'

const convertToJson = async (csvFilePath) => {
  const jsonArrayObj = await csv().fromFile(csvFilePath)
  console.log(jsonArrayObj);
}

convertToJson(csvFilePath)

We have the convertToJson function that takes a csvFilePath .

Then we call csv().fromFile with it to convert the CSV file content into a JSON object and assign that to jsonArrayObj .

As a result, jsonArrayObj is:

[
  { a: '1', b: '2', c: '3', d: '4' },
  { a: '5', b: '6', c: '7', d: '8' }
]

when we call it.

Categories
JavaScript Answers Nodejs

How to Get an Image from the Web and Encode it into a Base64 String with Node.js?

To get an image from the web and encode it into a base64 string with Node.js, we can use the Axios HTTP client to get the image and save it in a buffer object.

Then we can convert the saved buffer object into a base64 string.

To install Axios, we run:

npm i axios

Then we write:

const axios = require('axios')

const getImage = async () => {
  const image = await axios.get('https://picsum.photos/200/300', {
    responseType: 'arraybuffer'
  });
  const returnedB64 = Buffer.from(image.data).toString('base64');
  console.log(returnedB64)
}
getImage()

to import the axios package.

And then we create the getImage function that calls axios.get to make a GET request to get the image.

The 2nd argument sets the responseType to 'arraybuffer' so the image will be assigned to an array buffer with the image.

Next, we call Buffer.from with image.data to convert the array buffer object to a buffer.

Then we call toString with 'base64' to convert the buffer object to a base64 string and assign that to the returnedB64 variable.

Categories
JavaScript Answers Nodejs

How to Convert HTML to PDF with Node.js?

To convert HTML to PDF with Node.js, we can use the html-pdf library.

To use the library, we first install it by running:

npm i html-pdf

Then, we can write:

const pdf = require('html-pdf');
const html = `<b>hello world</b>`
const options = {
  format: 'Letter'
}

pdf.create(html, options).toFile('./pdfname.pdf', (err, res) => {
  if (err) {
    console.log(err);
  }
});

to use it by importing the library.

Then we add the html variable with the HTML string that we want to convert to a PDF file.

Next, set the options variable to an object that has some options for how to render the PDF.

Then we call pdf.create with html and options to render the HTML into a PDF with the given options.

The toFile method takes the file path to save the PDF to and a callback that runs when the PDF conversion is done.

err is defined when there’s an error with converting the PDF.

Therefore, we should see hello world in bold in the rendered PDF.