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

Kun*_*war 2 html javascript node.js

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');
Run Code Online (Sandbox Code Playgroud)

HTML 文件

<div class="container"></div>
Run Code Online (Sandbox Code Playgroud)

每当我尝试执行上面的代码时,它都会给我一个这样的错误

                  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)
Run Code Online (Sandbox Code Playgroud)

谁能告诉我如何才能实现同样的目标而不出现错误。

And*_*maz 7

上面的错误非常明显:

文档未定义

document不存在于Node(例如服务器)环境中,它仅存在于浏览器中

您将需要使用单独的库来解析您的 HTML 文件,以便执行诸如此类的查询querySelector('.container')

要查看的库(作为示例):

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

https://github.com/cheeriojs/cheerio