Categories
JavaScript Answers Nodejs

How to write in a text file without overwriting with Node.js and JavaScript?

Sometimes, we want to write in a text file without overwriting with Node.js and JavaScript.

In this article, we’ll look at how to write in a text file without overwriting with Node.js and JavaScript.

How to write in a text file without overwriting with Node.js and JavaScript?

To write in a text file without overwriting with Node.js and JavaScript, we can use the appendFile method.

For instance, we write:

const { promises: fs } = require("fs");

const write = async () => {
  await fs.appendFile("file.txt", 'abc')
}
write()

to call fs.appendFile with the path of the file to write to and the content to write into the file respectively.

The content will be added after the existing content of the file.

Conclusion

To write in a text file without overwriting with Node.js, we can use the appendFile method.

Categories
JavaScript Answers Nodejs

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

Sometimes, we want to get an image from the web and encode it into a base64 string with Node.js and JavaScript.

In this article, we’ll look at how to get an image from the web and encode it into a base64 string with Node.js and JavaScript.

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

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.

Conclusion

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.

Categories
JavaScript Answers Nodejs

How to Convert HTML to PDF with Node.js and JavaScript?

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

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

Convert HTML to PDF with Node.js and JavaScript

To convert HTML to PDF with Node.js and JavaScript, 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.

Conclusion

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

Categories
Express JavaScript Answers

How to Add a Single Routing Handler for Multiple Routes in a Single Line with JavaScript Express?

Sometimes, we want to add a single routing handler for multiple routes in a single line with JavaScript Express.

In this article, we’ll look at how to add a single routing handler for multiple routes in a single line with JavaScript Express.

Add a Single Routing Handler for Multiple Routes in a Single Line with JavaScript Express

To add a single routing handler for multiple routes in a single line with Express, we can pass in an array of route path patterns that will be handled by one route handler.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000

const routes = ['/', '/foo', '/bar', '/baz/:id']
app.get(routes, (req, res) => {
  res.send('hello world')
});

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

We have the routes array that has strings with different route path patterns.

And we use it as the first argument of the app.get method.

Therefore, when we go to / , /foo , /bar or /baz with anything after it, we’ll see hello world displayed.

This also works with app.post , app.delete , app.put , and other route defining methods.

Conclusion

To add a single routing handler for multiple routes in a single line with Express, we can pass in an array of route path patterns that will be handled by one route handler.

Categories
Express JavaScript Answers

How to Accept Multiple URL Parameters in JavaScript Express Routes?

Sometimes, we want to accept multiple URL parameters in JavaScript Express routes.

In this article, we’ll look at how to accept multiple URL parameters in JavaScript Express routes.

Accept Multiple URL Parameters in JavaScript Express Routes

To accept multiple URL parameters in JavaScript Express routes, we can put them as the placeholders for each URL parameter in the route path string.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000

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

app.get('/fruit/:fruitName/:fruitColor', (req, res) => {
  const {
    fruitName,
    fruitColor
  } = req.params
  res.json({
    fruitName,
    fruitColor
  });
});

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

We add the ‘/fruit/:fruitName/:fruitColor’ route, where :fruitName and :fruitColor are the URL params placeholders.

We can get the values of them from the req.params object.

Then, we return the extracted parameter values in the response object with res.json .

So if we make a GET request to /fruit/apple/green , we see:

{
    "fruitName": "apple",
    "fruitColor": "green"
}

returned as the response.