Categories
JavaScript Answers

How to fix document is not defined with Next.js and JavaScript?

To fix document is not defined with Next.js and JavaScript, we can disable server side rendering for specific components.

For instance, we write

import dynamic from "next/dynamic";

const DynamicComponentWithNoSSR = dynamic(
  () => import("../components/helloo"),
  { ssr: false }
);

function Home() {
  return (
    <div>
      <Header />
      <DynamicComponentWithNoSSR />
      <p>HOME PAGE is here!</p>
    </div>
  );
}

export default Home;

to import the hello component with import and disable server side rendering on it with { ssr: false }.

Then we can use it only in the browser environment.

Categories
JavaScript Answers

How to write base64 image-file with Node?

To write base64 image-file with Node, we call writeFile.

For instance, we write

const image = "data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAA..kJggg==";
const data = image.replace(/^data:image\/\w+;base64,/, "");

fs.writeFile(fileName, data, { encoding: "base64" }, (err) => {
  //...
});

to call writeFile with the MIME type part of the base64 string removed.

And we set encoding to 'base64' to convert the base64 string to binary content.

We get errors from err in the callback.

Categories
JavaScript Answers

How to check if a JSON is empty in Node?

To check if a JSON is empty in Node, we check if the object has any keys.

For instance, we write

const isEmptyObject = (obj) => {
  return !Object.keys(obj).length;
};

//...

if (isEmptyObject(query)) {
  // ...
} else {
  // ...
}

to define the isEmptyObject function.

In it, we call Object.keys to get the keys of obj in an array.

Then we check if its length is 0 to see if obj is empty.

Then we use an if statement to check if query is empty.

Categories
JavaScript Answers

How to add global variables for Node.js standard modules?

To add global variables for Node.js standard modules, we export the variables.

For instance, we write

const common = {
  util: require("util"),
  fs: require("fs"),
  path: require("path"),
};

module.exports = common;

to export the common object by setting it as the value of module.exports in common.js.

Then we write

const common = require("./common.js");
console.log(common.util.inspect(common));

to call require to include the exports in common.js in our code.

Categories
JavaScript Answers

How to get Node Socket.IO connected user count?

To get Node Socket.IO connected user count, we use the socketIO.engine.clientsCount property.

For instance, we write

const numClients = socketIO.engine.clientsCount;

to get the number of clients connected with socketIO.engine.clientsCount.