te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - How can I access DOM Elements using Node JS? - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I access DOM Elements using Node JS? - Stack Overflow

programmeradmin3浏览0评论

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.onplete (fs.js:171:23)

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

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.onplete (fs.js:171:23)

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

Share Improve this question asked Apr 25, 2021 at 14:28 Kunal TanwarKunal Tanwar 1,2911 gold badge12 silver badges30 bronze badges 5
  • 2 Simply, you cannot. There is no DOM on the server, just a plain html source file. – Bergi Commented Apr 25, 2021 at 14:39
  • 1 The "DOM" is the "Document Object Model", which is an in-memory representation of the HTML elements that were parsed by the browser. Node isn't a browser and so there is no DOM API available. – Scott Marcus Commented Apr 25, 2021 at 14:40
  • 1 Seems you are looking for some serverside HTML templating language, that allows you to dynamically generate HTML pages, e.g. with a list of icons from an array in them. – Bergi Commented Apr 25, 2021 at 14:41
  • @Bergi Yes! exactly this is what I need! Could you suggest any? – Kunal Tanwar Commented Apr 25, 2021 at 15:44
  • @KunalTanwar No, I dont want to suggest any. But with that search term, you'll find many libraries on the web, and can choose the one that you like best (for your particular use case) yourself. – Bergi Commented Apr 25, 2021 at 15:55
Add a ment  | 

4 Answers 4

Reset to default 8

The error above is very explicit:

document is not defined

document is not exist in Node (e.g. server) environment, it's exist only in browser.

You will need to use separate library to parse your HTML file in order to do queries like querySelector('.container') and etc.

Libraries to take a look (as an example):

https://github./taoqf/node-fast-html-parser

https://github./cheeriojs/cheerio

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.

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./questions/34309557/how-to-access-dom-using-node-js

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 piled 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!

发布评论

评论列表(0)

  1. 暂无评论