-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathnode_tutorial.html
More file actions
742 lines (721 loc) · 29.8 KB
/
node_tutorial.html
File metadata and controls
742 lines (721 loc) · 29.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Node.js Tutorial</title>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
<style>
/* General Styles */
body {
font-family: 'Arial', sans-serif;
background: #f4f4f4;
margin: 0;
padding: 0;
transition: 0.3s;
}
.dark-mode {
background: #222;
color: #fff;
}
header {
background: #2c3e50;
color: #fff;
padding: 10px 20px;
display: flex;
justify-content: space-between;
align-items: center;
position: sticky;
top: 0;
z-index: 1000;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
.logo {
font-size: 24px;
font-weight: bold;
color: #fff;
}
nav ul {
list-style: none;
margin: 0;
padding: 0;
display: flex;
align-items: center;
}
nav ul li {
margin-left: 25px;
}
nav ul li a {
color: #fff;
text-decoration: none;
font-weight: bold;
font-size: 16px;
transition: color 0.3s ease;
}
nav ul li a:hover {
color: #ff6f61;
}
.hamburger {
display: none;
font-size: 24px;
cursor: pointer;
}
.container {
max-width: 900px;
margin: 20px auto;
padding: 20px;
background: #fff;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.dark-mode .container {
background: #333;
box-shadow: 0 4px 8px rgba(255, 255, 255, 0.2);
}
h1 {
text-align: center;
color: #007bff;
}
.search-box {
padding: 10px;
width: 80%;
max-width: 400px;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 16px;
margin: 20px auto;
display: block;
}
.toggle-btn {
background: #008CBA;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
margin: 10px auto;
display: block;
transition: background 0.3s ease;
}
.toggle-btn:hover {
background: #005f73;
}
.section {
background: #f9f9f9;
padding: 15px;
margin: 10px 0;
border-radius: 10px;
cursor: pointer;
border-left: 5px solid #007bff;
transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.section:hover {
transform: translateY(-5px);
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
}
.content {
display: none;
padding: 15px;
background: #fff;
border-left: 5px solid #007bff;
color: black;
margin: 10px 0;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.dark-mode .content {
background: #444;
color: white;
border-left: 5px solid #008CBA;
}
pre {
background: #1e1e1e;
color: lime;
padding: 15px;
border-radius: 5px;
overflow-x: auto;
position: relative;
}
.copy-btn {
position: absolute;
top: 10px;
right: 10px;
background: #007bff;
color: white;
border: none;
padding: 5px 10px;
border-radius: 3px;
cursor: pointer;
transition: background 0.3s ease;
}
.copy-btn:hover {
background: #0056b3;
}
textarea {
width: 100%;
height: 100px;
font-family: monospace;
margin-top: 10px;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 14px;
}
.run-btn {
background: #28a745;
color: white;
padding: 8px 16px;
border: none;
border-radius: 5px;
cursor: pointer;
margin-right: 10px;
transition: background 0.3s ease;
}
.run-btn:hover {
background: #218838;
}
a {
display: block;
text-align: center;
margin-top: 20px;
padding: 10px;
color: white;
text-decoration: none;
border-radius: 5px;
transition: background 0.3s ease;
}
a:hover {
background: #0056b3;
}
footer {
background: #1a252f;
color: #fff;
text-align: center;
padding: 20px;
margin-top: 20px;
}
footer p {
margin: 0;
}
@media (max-width: 768px) {
.hamburger {
display: block;
}
nav ul {
display: none;
flex-direction: column;
width: 100%;
background: #2c3e50;
position: absolute;
top: 60px;
left: 0;
}
nav ul.active {
display: flex;
}
nav ul li {
margin: 10px 0;
text-align: center;
}
.header h3 {
font-size: 24px;
}
.search-box {
width: 90%;
}
}
</style>
</head>
<body>
<!-- Header -->
<header>
<div class="logo">Learn Coding</div>
<nav>
<ul class="menu">
<li><a href="index.html">Home</a></li>
<li><a href="javascript_tutorial.html">JavaScript Tutorial</a></li>
<li><a href="#tutorials">Tutorials</a></li>
<li><a href="#topics">Topics</a></li>
<li><a href="#testimonials">Testimonials</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
<div class="hamburger" onclick="toggleMenu()">☰</div>
</nav>
</header>
<!-- Main Content -->
<div class="container">
<h1>📌 Node.js Tutorial - Questions & Answers</h1>
<input type="text" id="search" class="search-box" placeholder="🔍 Search topics..." onkeyup="searchTopics()">
<button class="toggle-btn" onclick="toggleDarkMode()">🌙 Toggle Dark Mode</button>
<button class="toggle-btn" onclick="showRandomQuestion()">🎲 Random Question</button>
<button class="toggle-btn" onclick="exportQuestions()">💾 Export Questions</button>
<div id="topics-container"></div>
</div>
<!-- Footer -->
<footer id="contact">
<p>© 2023 Learn Coding. All rights reserved.</p>
</footer>
<script>
const topics = [
["What is Node.js?",
`Node.js is an open-source, cross-platform runtime environment that allows JavaScript to run outside the browser, primarily for server-side applications. Built on Chrome's V8 JavaScript engine, it uses an event-driven, non-blocking I/O model, making it lightweight and efficient for real-time applications like APIs, chat apps, and streaming services. Node.js enables developers to use JavaScript for both client and server, streamlining development.
<br><br><strong>Example:</strong><br>
<pre>
console.log('Hello, Node.js!');
</pre>
Save this as 'app.js' and run 'node app.js' to see the output.`],
["How to install Node.js?",
`Node.js can be installed by downloading the installer from the official website (nodejs.org) or using a package manager like Homebrew (Mac), apt (Ubuntu), or Chocolatey (Windows). The installer includes Node.js and npm (Node Package Manager). After installation, verify it by running 'node -v' and 'npm -v' in a terminal.
<br><br><strong>Example:</strong><br>
<pre>
// On Ubuntu
sudo apt update
sudo apt install nodejs npm
// Verify installation
node -v
npm -v
</pre>
This installs Node.js and checks the version.`],
["What is npm in Node.js?",
`npm (Node Package Manager) is the default package manager for Node.js, used to install, manage, and share JavaScript packages. It provides access to a vast registry of libraries (e.g., Express, Lodash) and allows developers to manage project dependencies via a 'package.json' file.
<br><br><strong>Example:</strong><br>
<pre>
// Initialize a project
npm init -y
// Install a package
npm install express
</pre>
This creates a 'package.json' and installs Express.`],
["How to create a basic server in Node.js?",
`Node.js provides the built-in 'http' module to create a web server. You can define routes, handle requests, and send responses. The server listens on a specified port for incoming HTTP requests.
<br><br><strong>Example:</strong><br>
<pre>
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\\n');
});
server.listen(3000, () => console.log('Server running on port 3000'));
</pre>
Run this and visit 'http://localhost:3000' to see the response.`],
["What is Express.js?",
`Express.js is a minimal and flexible web framework for Node.js, simplifying the creation of web servers and APIs. It provides middleware, routing, and utilities for handling HTTP requests and responses.
<br><br><strong>Example:</strong><br>
<pre>
const express = require('express');
const app = express();
app.get('/', (req, res) => res.send('Hello, Express!'));
app.listen(3000, () => console.log('Server running on port 3000'));
</pre>
Install Express with 'npm install express' and run this code.`],
["What is Middleware in Express?",
`Middleware functions in Express are functions that execute during the request-response cycle, with access to the request (req), response (res), and next middleware (next). They can modify requests, validate data, or handle errors.
<br><br><strong>Example:</strong><br>
<pre>
const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log('Request received at:', new Date());
next();
});
app.get('/', (req, res) => res.send('Hello!'));
app.listen(3000);
</pre>
This logs the timestamp of each request.`],
["How to handle JSON data in Node.js?",
`Express provides 'express.json()' middleware to parse incoming JSON requests. You can access the parsed data via 'req.body' in your routes.
<br><br><strong>Example:</strong><br>
<pre>
const express = require('express');
const app = express();
app.use(express.json());
app.post('/data', (req, res) => {
res.json({ received: req.body });
});
app.listen(3000);
</pre>
Send a POST request with JSON to '/data' to see the response.`],
["How to connect Node.js with MongoDB?",
`Mongoose is an ODM (Object Data Modeling) library for MongoDB and Node.js, simplifying database interactions. You connect to MongoDB using a connection string and define schemas for data.
<br><br><strong>Example:</strong><br>
<pre>
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mydb', { useNewUrlParser: true });
const User = mongoose.model('User', new mongoose.Schema({ name: String }));
const user = new User({ name: 'Alice' });
user.save().then(() => console.log('User saved'));
</pre>
Install Mongoose with 'npm install mongoose'.`],
["How to create a REST API in Node.js?",
`A REST API in Node.js is typically built with Express, defining endpoints for CRUD operations (Create, Read, Update, Delete). Routes handle HTTP methods like GET, POST, PUT, DELETE.
<br><br><strong>Example:</strong><br>
<pre>
const express = require('express');
const app = express();
app.use(express.json());
let users = [];
app.get('/users', (req, res) => res.json(users));
app.post('/users', (req, res) => {
users.push(req.body);
res.status(201).json(req.body);
});
app.listen(3000);
</pre>
This creates a simple REST API for users.`],
["How to use Environment Variables in Node.js?",
`Environment variables store configuration settings (e.g., API keys) securely. The 'dotenv' package loads variables from a '.env' file into 'process.env'.
<br><br><strong>Example:</strong><br>
<pre>
// .env file
PORT=3000
// index.js
require('dotenv').config();
const express = require('express');
const app = express();
app.listen(process.env.PORT, () => console.log('Server on port ' + process.env.PORT));
</pre>
Install dotenv with 'npm install dotenv'.`],
["What is Asynchronous Programming in Node.js?",
`Node.js uses an event-driven, non-blocking I/O model, allowing asynchronous operations (e.g., file reading, HTTP requests) to run without blocking the main thread. Callbacks, Promises, and Async/Await handle async code.
<br><br><strong>Example:</strong><br>
<pre>
const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
</pre>
This reads a file asynchronously.`],
["How to use Async/Await in Node.js?",
`Async/Await simplifies asynchronous code by allowing you to write it like synchronous code. Functions marked 'async' return Promises, and 'await' pauses execution until the Promise resolves.
<br><br><strong>Example:</strong><br>
<pre>
const fs = require('fs').promises;
async function readFile() {
try {
const data = await fs.readFile('file.txt', 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
}
readFile();
</pre>
This reads a file using Async/Await.`],
["What is WebSocket in Node.js?",
`WebSocket is a protocol for real-time, bi-directional communication between client and server over a single, persistent connection. Unlike HTTP, it allows both parties to send data at any time.
<br><br><strong>Example:</strong><br>
WebSocket is typically implemented using the 'ws' library in Node.js.`],
["How does WebSocket work?",
`WebSocket starts with an HTTP handshake (using the 'Upgrade' header) to establish a persistent connection. Once established, both client and server can send messages anytime, ideal for real-time apps like chat or live notifications.
<br><br><strong>Example:</strong><br>
<pre>
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', ws => {
ws.on('message', message => console.log('Received:', message));
ws.send('Welcome to WebSocket!');
});
</pre>
Install 'ws' with 'npm install ws' and run this server.`],
["Why use WebSocket?",
`WebSockets reduce latency by maintaining a single connection, unlike HTTP’s request-response cycle. They’re ideal for real-time applications like chat, gaming, live updates, or collaborative tools due to their efficiency and bi-directional nature.`],
["How to implement WebSocket in Node.js?",
`The 'ws' library is commonly used to create a WebSocket server in Node.js. It handles connections, messages, and events like 'open' and 'close'.
<br><br><strong>Example:</strong><br>
<pre>
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', ws => {
ws.on('message', message => {
ws.send('Echo: ' + message);
});
});
</pre>
This echoes messages back to the client.`],
["Example WebSocket setup?",
`To set up a WebSocket server, install the 'ws' package and create a server that listens for connections. Clients connect using the WebSocket API in the browser.
<br><br><strong>Example:</strong><br>
<pre>
// Server (server.js)
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', ws => {
ws.send('Connected!');
});
// Client (HTML)
const ws = new WebSocket('ws://localhost:8080');
ws.onmessage = event => console.log(event.data);
</pre>
Run 'npm install ws' and start the server.`],
["How does the WebSocket client communicate?",
`A WebSocket client (e.g., in a browser) connects to a server using 'new WebSocket(url)'. It listens for events like 'open', 'message', 'close', and sends data with 'socket.send()'.
<br><br><strong>Example:</strong><br>
<pre>
const ws = new WebSocket('ws://localhost:8080');
ws.onopen = () => ws.send('Hello, Server!');
ws.onmessage = event => console.log('Received:', event.data);
ws.onclose = () => console.log('Disconnected');
</pre>
This client connects and communicates with a WebSocket server.`],
["How to use JWT for Authentication?",
`JSON Web Tokens (JWT) are used for secure authentication. A token is generated on the server, signed with a secret, and sent to the client. The client includes it in requests to verify identity.
<br><br><strong>Example:</strong><br>
<pre>
const jwt = require('jsonwebtoken');
const express = require('express');
const app = express();
app.use(express.json());
app.post('/login', (req, res) => {
const token = jwt.sign({ userId: 1 }, 'secret');
res.json({ token });
});
app.listen(3000);
</pre>
Install 'jsonwebtoken' with 'npm install jsonwebtoken'.`],
["What is Redis and How to Use it in Node.js?",
`Redis is an in-memory data store used for caching, session management, or real-time analytics. In Node.js, the 'redis' package connects to a Redis server.
<br><br><strong>Example:</strong><br>
<pre>
const redis = require('redis');
const client = redis.createClient();
client.set('key', 'value', redis.print);
client.get('key', (err, value) => console.log(value));
</pre>
Install 'redis' with 'npm install redis' and run a Redis server.`],
["What is Event Emitter in Node.js?",
`The EventEmitter class enables event-driven programming in Node.js. Objects can emit named events, and listeners can handle them, useful for asynchronous operations.
<br><br><strong>Example:</strong><br>
<pre>
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('greet', name => console.log('Hello, ' + name));
emitter.emit('greet', 'Alice');
</pre>
This emits and handles a custom 'greet' event.`],
["How to Handle Errors in Node.js?",
`Errors in Node.js can be handled using try-catch for synchronous code, error-first callbacks, or Promise error handling. Express provides middleware for centralized error handling.
<br><br><strong>Example:</strong><br>
<pre>
const express = require('express');
const app = express();
app.get('/error', (req, res, next) => {
next(new Error('Something went wrong'));
});
app.use((err, req, res, next) => {
res.status(500).send(err.message);
});
app.listen(3000);
</pre>
This handles errors in an Express app.`],
["What is Nodemon and Why Use It?",
`Nodemon is a development tool that automatically restarts a Node.js server when code changes, improving development efficiency.
<br><br><strong>Example:</strong><br>
<pre>
// Install nodemon
npm install -g nodemon
// Run server
nodemon server.js
</pre>
Nodemon watches for file changes and restarts the server.`],
["What is the Difference Between Process.nextTick() and setImmediate()?",
`Both schedule callbacks, but 'process.nextTick()' runs before the next event loop phase, potentially delaying I/O, while 'setImmediate()' runs in the next event loop cycle, after I/O.
<br><br><strong>Example:</strong><br>
<pre>
process.nextTick(() => console.log('Next tick'));
setImmediate(() => console.log('Immediate'));
console.log('Main');
</pre>
Output: Main, Next tick, Immediate.`],
["How to Deploy a Node.js App?",
`Deploying a Node.js app involves hosting it on a server (e.g., AWS, Heroku). PM2 manages processes, and Nginx can act as a reverse proxy for load balancing.
<br><br><strong>Example:</strong><br>
<pre>
// Install PM2
npm install -g pm2
// Start app with PM2
pm2 start server.js
</pre>
This runs a Node.js app with PM2 for process management.`]
];
const menuData = [
{
title: "Basic Math",
subMenu: [
{ name: "Trigonometry", link: "Trigonometry" },
{ name: "Algebra", link: "Algebra" },
{ name: "Geometry", link: "Geometry" },
]
},
{
title: "Tutorial",
subMenu: [
{ name: "React.js Tutorial", link: "react_tutorial" },
{ name: "Node.js Tutorial", link: "node_tutorial" },
{ name: "JavaScript Tutorial", link: "JavaScript_tutorial" }
]
}
];
const menuContainer = document.querySelector('.menu');
menuData.forEach(menuItem => {
const li = document.createElement('li');
const a = document.createElement('a');
a.href = `#${menuItem.title.toLowerCase()}`;
a.textContent = menuItem.title;
const subMenu = document.createElement('ul');
subMenu.classList.add('sub-menu');
menuItem.subMenu.forEach(subItem => {
subMenu.innerHTML += `<li><a href="${subItem.link}">${subItem.name}</a></li>`;
});
li.appendChild(a);
li.appendChild(subMenu);
menuContainer.appendChild(li);
});
// Initialize bookmarked and viewed questions from localStorage
let bookmarkedQuestions = JSON.parse(localStorage.getItem('bookmarkedQuestions')) || [];
let viewedQuestions = JSON.parse(localStorage.getItem('viewedQuestions')) || [];
let sectionStates = JSON.parse(localStorage.getItem('sectionStates')) || {};
// Render topics with bookmark and viewed indicators
const topicsContainer = document.getElementById('topics-container');
topics.forEach((topic, index) => {
const isBookmarked = bookmarkedQuestions.includes(index);
const isViewed = viewedQuestions.includes(index);
topicsContainer.innerHTML += `
<div class="section" onclick="toggleContent('q${index + 1}', ${index})">
<h2>
${index + 1}️⃣ ${topic[0]}
${isBookmarked ? '<span style="color: gold;">⭐</span>' : ''}
${isViewed ? '<span style="color: green;">✔</span>' : ''}
</h2>
<button class="copy-btn" onclick="bookmarkQuestion(${index}); event.stopPropagation();">
${isBookmarked ? 'Remove Bookmark' : 'Bookmark'}
</button>
</div>
<div id="q${index + 1}" class="content">
<p>${topic[1]}</p>
<textarea id="code${index + 1}">${topic[1]}</textarea><br>
<button class="run-btn" onclick="runCode('code${index + 1}')">Run</button>
<button class="copy-btn" onclick="copyToClipboard('code${index + 1}')">Copy</button>
</div>
`;
});
// Restore section states
Object.keys(sectionStates).forEach(id => {
const content = document.getElementById(id);
if (content && sectionStates[id]) {
content.style.display = 'block';
}
});
function toggleContent(id, index) {
let content = document.getElementById(id);
content.style.display = (content.style.display === 'none' || content.style.display === '') ? 'block' : 'none';
sectionStates[id] = content.style.display === 'block';
localStorage.setItem('sectionStates', JSON.stringify(sectionStates));
// Mark question as viewed
if (!viewedQuestions.includes(index)) {
viewedQuestions.push(index);
localStorage.setItem('viewedQuestions', JSON.stringify(viewedQuestions));
updateSectionIndicators(index);
}
}
function bookmarkQuestion(index) {
if (bookmarkedQuestions.includes(index)) {
bookmarkedQuestions = bookmarkedQuestions.filter(i => i !== index);
Swal.fire('Bookmark removed!');
} else {
bookmarkedQuestions.push(index);
Swal.fire('Question bookmarked!');
}
localStorage.setItem('bookmarkedQuestions', JSON.stringify(bookmarkedQuestions));
updateSectionIndicators(index);
}
function updateSectionIndicators(index) {
const section = document.getElementsByClassName('section')[index];
const isBookmarked = bookmarkedQuestions.includes(index);
const isViewed = viewedQuestions.includes(index);
section.querySelector('h2').innerHTML = `
${index + 1}️⃣ ${topics[index][0]}
${isBookmarked ? '<span style="color: gold;">⭐</span>' : ''}
${isViewed ? '<span style="color: green;">✔</span>' : ''}
`;
section.querySelector('.copy-btn').textContent = isBookmarked ? 'Remove Bookmark' : 'Bookmark';
}
function toggleDarkMode() {
document.body.classList.toggle('dark-mode');
Swal.fire('🌙 Dark mode ' + (document.body.classList.contains('dark-mode') ? 'enabled' : 'disabled'));
localStorage.setItem('darkMode', document.body.classList.contains('dark-mode'));
}
function searchTopics() {
let input = document.getElementById('search').value.toLowerCase();
let sections = document.getElementsByClassName('section');
for (let section of sections) {
section.style.display = section.textContent.toLowerCase().includes(input) ? '' : 'none';
}
}
function copyToClipboard(codeId) {
let codeElement = document.getElementById(codeId);
codeElement.select();
document.execCommand('copy');
Swal.fire('✅ Code copied!');
}
function runCode(codeId) {
let code = document.getElementById(codeId).value;
try {
eval(code);
} catch (error) {
Swal.fire('❌ Error: ' + error.message);
}
}
function showRandomQuestion() {
const randomIndex = Math.floor(Math.random() * topics.length);
const sections = document.getElementsByClassName('section');
for (let section of sections) {
section.style.display = 'none';
}
sections[randomIndex].style.display = '';
toggleContent(`q${randomIndex + 1}`, randomIndex);
Swal.fire(`Showing Question ${randomIndex + 1}`);
}
function exportQuestions() {
const data = topics.map(([question, answer]) => ({ question, answer }));
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'nodejs_tutorial_questions.json';
a.click();
URL.revokeObjectURL(url);
Swal.fire('Questions exported as JSON!');
}
function toggleMenu() {
const menu = document.querySelector('.menu');
menu.classList.toggle('active');
}
// Keyboard shortcuts
document.addEventListener('keydown', (e) => {
if (e.ctrlKey && e.key === 'd') {
e.preventDefault();
toggleDarkMode();
}
if (e.ctrlKey && e.key === 's') {
e.preventDefault();
document.getElementById('search').focus();
}
if (e.ctrlKey && e.key === 'r') {
e.preventDefault();
showRandomQuestion();
}
if (e.ctrlKey && e.key === 'e') {
e.preventDefault();
exportQuestions();
}
});
// Restore dark mode preference
if (localStorage.getItem('darkMode') === 'true') {
document.body.classList.add('dark-mode');
}
</script>
</body>
</html>