Categories
JavaScript Answers

How to convert CSV to JSON in Node.js?

Sometimes, we want to convert CSV to JSON in Node.js.

In this article, we’ll look at how to convert CSV to JSON in Node.js.

How to convert CSV to JSON in Node.js?

To convert CSV to JSON in Node.js, we can use the csvtojson module.

To install it, we run

npm i csvtohjson

Then we use it by writing

const csv = require("csvtojson");

csv()
  .fromStream(readableStream)
  .subscribe((jsonObj) => {
    console.log(jsonObj)
  })

const csvToJson = async () => {
  const jsonArray = await csv().fromFile(filePath);
}

to call fromStream with a readableStream to read the CSV data from the stream.

Then we call subscribe with a callback to get the JSON converted from the CSV with jsonObj.

Also, we can use csv().fromFile with a CSV filePath to convert the CSV file at filePath to a JSON object by returning a promise with the JSON object.

We then get the JSON result with await.

Conclusion

To convert CSV to JSON in Node.js, we can use the csvtojson module.

Categories
JavaScript Answers

How to turn all the keys of an object to lower case with JavaScript?

Sometimes, we want to turn all the keys of an object to lower case with JavaScript.

In this article, we’ll look at how to turn all the keys of an object to lower case with JavaScript.

How to turn all the keys of an object to lower case with JavaScript?

To turn all the keys of an object to lower case with JavaScript, we can use the Object.entries and Object.fromEntries method and the string toLowerCase method.

For instance, we write

const newObj = Object.fromEntries(
  Object.entries(obj).map(([k, v]) => [k.toLowerCase(), v])
);

to call Object.fromEntries with the array returned by Object.entries and map.

Object.entries returns the key-value pairs in obj as an array of key-value pair arrays.

Therefore, we can call map on the returned array to return the lower case version of key k with k.toLowerCase.

Then we call Object.fromEntries to convert the array of key value pairs with the keys in lower case back to an object and assign it to newObj.

Conclusion

To turn all the keys of an object to lower case with JavaScript, we can use the Object.entries and Object.fromEntries method and the string toLowerCase method.

Categories
JavaScript Answers

How to check if token expired using the Node.js JWT library?

Sometimes, we want to check if token expired using the Node.js JWT library.

In this article, we’ll look at how to check if token expired using the Node.js JWT library.

How to check if token expired using the Node.js JWT library?

To check if token expired using the Node.js JWT library, we can use the jwt.verify method.

For instance, we write

const jwt = require('jsonwebtoken')
const util = require('util');
const jwtVerifyAsync = util.promisify(jwt.verify);

router.use(async (req, res, next) => {
  const token = getToken(req)
  try {
    req.auth = await jwtVerifyAsync(token, req.app.get('your-secret'))
  } catch (err) {
    throw new Error(err)
  }
  next()
});

to call util.promisify to convert the jwt.verify method to a function that returns a promise and assign it to jwtVerifyAsync.

Then we call jwtVerifyAsync with the token and the token secret to check if the token is valid.

If it’s expired, then it’s considered invalid and an error will be thrown.

And when an error is thrown we use the catch block to catch it and rethrow it with throw.

Otherwise, we call next to call the next middleware.

Conclusion

To check if token expired using the Node.js JWT library, we can use the jwt.verify method.

Categories
JavaScript Answers

How to get image from web and encode with base64 with Node.js?

Sometimes, we want to get image from web and encode with base64 with Node.js.

In this article, we’ll look at how to get image from web and encode with base64 with Node.js.

How to get image from web and encode with base64 with Node.js?

To get image from web and encode with base64 with Node.js, we can use the http.get method.

For instance, we write

const http = require('http');

http.get('https://picsum.photos/200/300', (resp) => {
  resp.setEncoding('base64');
  let body = `data:${resp.headers["content-type"]};base64,`;

  resp.on('data', (data) => {
    body += data
  });
  resp.on('end', () => {
    console.log(body);
  });
}).on('error', (e) => {
  console.log(`Got error: ${e.message}`);
});

to define the body in the http.get callback.

We call resp.on with 'data' to listen for the data event which has the response chunks in the data parameter of the data event callback.

We concatenate that to body and then we can get the whole response from the end event callback, which is

resp.on('end', () => {
  console.log(body);
});

Conclusion

To get image from web and encode with base64 with Node.js, we can use the http.get method.

Categories
JavaScript Answers

How to convert HTML to PDF with Node.js?

Sometimes, we want to convert HTML to PDF with Node.js.

In this article, we’ll look at how to convert HTML to PDF with Node.js.

How to convert HTML to PDF with Node.js?

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

To install it, we run

npm i html-pdf

Then we write

const pdf = require('html-pdf');


pdf.create(html, config).toFile('path/to/output/generated.pdf', (err, res) => {
  if (err) {
    return console.log(err);
  }
  console.log(res);
});

to call pdf.create with the html string to convert to a PDF.

And then we call toFile to write the PDF content to a file on disk.

The callback’s res parameter has the results of writing the PDF.

And err has the errors.

Conclusion

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