Categories
JavaScript Answers

How to fix JavaScript Date().getTime() is not a function?

To fix JavaScript Date().getTime() is not a function, we need the new keyword before Date.

For instance, we write

const now = new Date().getTime();

to create a new date object with new Date().

And then we call getTime to get the current timestamp from the date object.

Categories
JavaScript Answers

How to access EJS variable in JavaScript logic?

To access EJS variable in JavaScript logic, we can inject the variable directly into the EJS template.

For instance, we write

<% if (gameState) { %>
<script>
  let clientGameState = <%= gameState %>
</script>
<% } %>

to get the gameState variable with <%= gameState %> and assign that to the clientGameState variable in the script tag.

Categories
JavaScript Answers

How to add multiple classes with function with d3 and JavaScript?

To add multiple classes with function with d3 and JavaScript, we use the attr method.

For instance, we write

d3.selectAll(".user").attr("data-name", (d, i) => {
  return `Michael #${i}`;
});

to select all elements with class user with selectAll.

And then we call attr with the attribute name we want to set for each selected element.

The callback returns the value of the data-name attribute. And i is the index of the element being iterated through to set the attribute.

Categories
JavaScript Answers

How to run HTML file using Node.js?

To run HTML file using Node.js, we call readFile to read the file and http module.

For instance, we write

const http = require("http");
const fs = require("fs");

const PORT = 8080;

fs.readFile("./index.html", (err, html) => {
  if (err) throw err;

  http
    .createServer((request, response) => {
      response.writeHeader(200, { "Content-Type": "text/html" });
      response.write(html);
      response.end();
    })
    .listen(PORT);
});

to call readFile to read index.html.

And then we serv it by call http.createServer to start a web server with a callback that calls write with the html file content to serve that.

Categories
JavaScript Answers

How to query for entries with columns that are not null with JavaScript Sequelize?

To query for entries with columns that are not null with JavaScript Sequelize, we use the Op.ne property.

For instance, we write

Post.update(
  {
    updatedAt: null,
  },
  {
    where: {
      deletedAt: {
        [Op.ne]: null,
      },
    },
  }
);

to select the entries that have the deletedAt field set to a non-null value with Op.ne.

And then we call update with an object to set updatedAt to null for entries that match the condition.