Categories
JavaScript Answers

How to enable CORS in production with Nest.js?

To enable CORS in production with Nest.js, we call the enableCors method.

For instance, we write

const app = await NestFactory.create(ApplicationModule);
app.enableCors();
await app.listen(3000);

to call create to create a Nest.js app.

Then we call enableCors to enable CORS on the app.

Categories
JavaScript Answers

How to add a time delayed redirect with JavaScript?

To add a time delayed redirect with JavaScript, we call setTimeout.

For instance, we write

setTimeout(() => {
  window.location.href = "/blog";
}, 2000);

to call setTimeout with a callback to redirect to the /blog page after 2000 milliseconds.

Categories
JavaScript Answers

How to get the day of the week from the day number in JavaScript?

To get the day of the week from the day number in JavaScript, we use the date getDay method.

For instance, we write

const dayOfTheWeek = (day, month, year) => {
  const weekday = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
  ];
  return weekday[new Date(`${month}/${day}/${year}`).getDay()];
};

console.log(dayOfTheWeek(3, 11, 2022));

to define the dayOfTheWeek function.

In it, we put the month, day and year into a string to create a Date object from it.

Then we call getDay to get the day of the week with 0 being Sunday, 1 being Monday, etc.

We use that returned number as the index of weekday to get the day of the week.

Categories
JavaScript Answers

How to get the day of the week from the day number in JavaScript?

To get the day of the week from the day number in JavaScript, we call the toLocaleString method.

For instance, we write

const weekday = new Date().toLocaleString("en-us", { weekday: "long" });

to call toLocaleString on a date object with the locale and an object specifying the date string returned.

We set weekday to 'long' to return the day of the week.

Categories
JavaScript Answers

How to send a PDF file directly to the printer using JavaScript?

To send a PDF file directly to the printer using JavaScript, we create an object URL.

For instance, we write

const dataUrl = window.URL.createObjectURL(file);
const pdfWindow = window.open(dataUrl);
pdfWindow.print();

to call createObjectURL with the PDF file to create the PDF file object URL string.

Then we open the dataUrl in a window wiith window.open.

Finally, we call print to open the print dialog to print the PDF.