Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
171
rated 0 times [  178] [ 7]  / answers: 1 / hits: 10968  / 3 Years ago, sun, april 25, 2021, 12:00:00

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 Finalbackendserver.js:26:19
at Array.forEach (<anonymous>)
at D:Framework Finalbackendserver.js:23:13
at FSReqCallback.oncomplete (fs.js:171:23)

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


More From » html

 Answers
4

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.com/taoqf/node-fast-html-parser


https://github.com/cheeriojs/cheerio


[#1430] Tuesday, April 20, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
carlton

Total Points: 373
Total Questions: 123
Total Answers: 97

Location: Saint Helena
Member since Wed, Nov 9, 2022
2 Years ago
carlton questions
Wed, Feb 17, 21, 00:00, 3 Years ago
Tue, Oct 27, 20, 00:00, 4 Years ago
Tue, Oct 13, 20, 00:00, 4 Years ago
Mon, Apr 13, 20, 00:00, 4 Years ago
;