简体   繁体   English

如何使用 Node JS 访问 DOM 元素?

[英]How can I access DOM Elements using Node JS?

JAVASCRIPT FILE JAVASCRIPT文件

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 HTML 文件

<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.谁能告诉我如何在不出错的情况下实现相同的目标。

In NodeJS, the document Object doesn't exist.在 NodeJS 中,文档 Object 不存在。 You can't access DOM-Nodes or anything in the DOM in NodeJS .您不能NodeJS中访问 DOM 节点或 DOM 中的任何内容。

NodeJS is serverside Javascript. NodeJS 是服务器端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).要在 NodeJS 中设置服务器,请使用Express (经常使用)。 Google about it.谷歌一下。

The error above is very explicit:上面的错误非常明确:

document is not defined文档未定义

document is not exist in Node (eg 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.您将需要使用单独的库来解析您的 HTML 文件,以便执行querySelector('.container')等查询。

Libraries to take a look (as an example):库来看看(例如):

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

https://github.com/cheeriojs/cheerio https://github.com/cheeriojs/cheerio

Node.js is server side, the document doesn't exist. Node.js 是服务器端,文档不存在。 So the Dom doesn't exist.所以Dom不存在。 You need to try with client web browser side.您需要尝试使用客户端 web 浏览器端。 I mean simply just create a web page document我的意思是只需创建一个 web 页面文档

But you can also check this answer for more information但是您也可以查看此答案以获取更多信息

stackoverflow.com/questions/34309557/how-to-access-dom-using-node-js stackoverflow.com/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.我正在做 Jest 测试,其中一些测试必须操作 DOM 元素。 What it works for me was instal JSDOM and follow instructions of basic usage.它对我有用的是安装 JSDOM 并遵循基本使用说明。 JSDOM JSDOM

npm i 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)); 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错误:模块 '\?\C:\Users\pc\node_modules\canvas\build\Release\canvas.node' 是针对不同的 Node.js 版本使用 NODE_MODULE_VERSION 72 编译的。此版本的 Node.js 需要

I am not shure if it is because I am using a Windows, but I just install canvas:我不确定是不是因为我使用的是 Windows,但我只是安装了 canvas:

npm install canvas npm 安装 canvas

(In fact in the JSDOM doc file on Git Hub It talks about that) JSDOM (其实在Git Hub上的JSDOM doc文件里有讲过) JSDOM

In my case It show me some high severity vulnerabilities so I just run:就我而言,它向我展示了一些严重程度高的漏洞,所以我只运行:

npm audit fix npm 审计修复

If that doesn´t resolve the issue, you need to force it: npm audit fix --force如果这不能解决问题,您需要强制执行:npm audit fix --force

after that it shows me succesfull and I was able to use the JSDOM as it is specified in the JSDOM info page.之后它显示我成功并且我能够使用 JSDOM,因为它在 JSDOM 信息页面中指定。

I hope this information helps you!我希望这些信息对你有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM