'How can I access DOM Elements using Node JS?

JAVASCRIPT FILE

const path = require('path');
const http = require('http');
const fs = require('fs');

const dir = '../frontend/';

const server = http.createServer((request, respond) => {
      console.log(request.url);

      respond.writeHead(200, {
            'Content-Type': 'text/html',
      });

      const readStream = fs.createReadStream(dir + 'index.html', 'utf-8');
      readStream.pipe(respond);
});

const icons = 'icons/';

fs.readdir(icons, (error, files) => {
      if (error) throw error;

      files.forEach((file) => {
            if (path.extname(file) == '.svg') {
                  // I want to append this filename in the DOM Element.
                  document.querySelector('.container').innerHTML = file; // Like This
                  // console.log(file); 
            }
      });
});

server.listen(3000, 'localhost');

HTML File

<div class="container"></div>

Whenever I'm trying to execute above code it gives me an error like this

                  document.querySelector('.container').innerHTML = file;
                  ^

ReferenceError: document is not defined
    at D:\Framework Final\backend\server.js:26:19
    at Array.forEach (<anonymous>)
    at D:\Framework Final\backend\server.js:23:13
    at FSReqCallback.oncomplete (fs.js:171:23)

Can anyone tell me how can I achieve the same without getting an error.



Solution 1:[1]

In NodeJS, the document Object doesn't exist. You can't access DOM-Nodes or anything in the DOM in NodeJS.

NodeJS is serverside Javascript.

If you want any data from the client, you have to add client-side code and send the data from the client to the server. This is done with a post-request. In the Backend, you have to setup a server with routes. To setup a server in NodeJS, use Express (frequently used). Google about it.

Solution 2:[2]

Node.js is server side, the document doesn't exist. So the Dom doesn't exist. You need to try with client web browser side. I mean simply just create a web page document

But you can also check this answer for more information

stackoverflow.com/questions/34309557/how-to-access-dom-using-node-js

Solution 3:[3]

I had an issue similar to this. I was working whit Jest tests and some of the tests have to manipulate DOM elements. What it works for me was install JSDOM and follow instructions of basic usage. JSDOM

npm i jsdom

After that, when I run the test It shows me this error:

node:internal/modules/cjs/loader:1183
  return process.dlopen(module, path.toNamespacedPath(filename));
                 ^

Error: The module '\\?\C:\Users\pc\node_modules\canvas\build\Release\canvas.node'
was compiled against a different Node.js version using
NODE_MODULE_VERSION 72. This version of Node.js requires

I am not sure if it is because I am using a Windows, but I just installed canvas:

npm install canvas

(In fact in the JSDOM doc file on Git Hub It talks about that) JSDOM

In my case It show me some high severity vulnerabilities so I just run:

npm audit fix 

If that doesn't resolve the issue, you need to force it:

npm audit fix --force

after that it shows me successful and I was able to use the JSDOM as it is specified in the JSDOM info page.

I hope this information helps you!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dyvd
Solution 2
Solution 3 Daniel