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.

Categories
JavaScript Answers

How to use MongoDB with promises in Node.js?

Sometimes, we want to use MongoDB with promises in Node.js.

In this article, we’ll look at how to use MongoDB with promises in Node.js.

How to use MongoDB with promises in Node.js?

To use MongoDB with promises in Node.js, we can use the MongoDB client methods with async and await.

For instance, we write

const {
  MongoClient
} = require('mongodb')

const connect = async () => {
  const url = 'mongodb://localhost:27017/example'
  const db = await MongoClient.connect(url)
  console.log(db)
}

to call MongoClient.connect with the database url to connect to the database at the given URL.

Then we get the db database connection handle with await.

await returns the resolve value from the promise returned by connect.

Conclusion

To use MongoDB with promises in Node.js, we can use the MongoDB client methods with async and await.

Categories
JavaScript Answers

How to create a basic static file server in Node.js?

Sometimes, we want to create a basic static file server in Node.js.

In this article, we’ll look at how to create a basic static file server in Node.js.

How to create a basic static file server in Node.js?

To create a basic static file server in Node.js, we can use Express.

To install it, we run

npm i express

Then we create a static file server with it by writing

const express = require('express')
const app = express()
const port = process.env.PORT || 4000;

app.use(express.static(__dirname + '/public'));
app.listen(port);

We call express.static with the folder with the static files we want to serve.

And we call app.use to use the middleware returned by express.static.

Then we call app.listen with port to start the server and listen at for traffic at the given port.

Conclusion

To create a basic static file server in Node.js, we can use Express.

Categories
JavaScript Answers

How to create document if not exists, otherwise, update and return document in either case with Mongoose?

Sometimes, we want to create document if not exists, otherwise, update and return document in either case with Mongoose.

In this article, we’ll look at how to create document if not exists, otherwise, update and return document in either case with Mongoose.

How to create document if not exists, otherwise, update and return document in either case with Mongoose?

To create document if not exists, otherwise, update and return document in either case with Mongoose, we can use the findOneAndUpdate method.

For instance, we write

const query = {}
const update = {
  expire: new Date()
}
const options = {
  upsert: true,
  new: true,
  setDefaultsOnInsert: true
};

Model.findOneAndUpdate(query, update, options, (error, result) => {
  if (error) {
    return;
  }
});

to call findOneAndUpdate with the query, update, options and a callback.

query has the query to find the item to update.

update is an object that has the fields with the values we want to update.

options has upsert set to true to find an existing document if it exists or create a new one.

new is set to true to create a new document if it doesn’t exist.

The result parameter in the callback should have the latest document value.

Conclusion

To create document if not exists, otherwise, update and return document in either case with Mongoose, we can use the findOneAndUpdate method.