Node.js入门疑问:如何像PHP那样创建动态网页?
Hey there! As someone who made the switch from PHP to Node.js early on, I totally get that urge to replicate that "write code right in your HTML" workflow you’re used to. Let me break down exactly how to do this in Node.js, with a hands-on example that’ll feel familiar.
The Core Idea: Template Engines
Unlike PHP, where your web server directly parses files with embedded <?php ?> code, Node.js relies on template engines to mix JavaScript logic with HTML. These engines let you embed dynamic code in your markup, just like PHP—some even use syntax that’s nearly identical.
My Top Pick for PHP Devs: EJS
EJS (Embedded JavaScript) is perfect because its syntax mirrors PHP’s almost exactly. Let’s walk through setting it up step by step:
Set Up Your Node.js Project
First, create a new folder, open it in your terminal, and initialize a project:npm init -yThen install the two packages we need: Express (to handle web requests) and EJS (the template engine):
npm install express ejsCreate Your Express Server
Make a file calledapp.jswith this code:const express = require('express'); const app = express(); // Tell Express we're using EJS as our template engine app.set('view engine', 'ejs'); // Optional: Specify where your template files live (defaults to a "views" folder) app.set('views', './views'); // Define a route that renders a dynamic page app.get('/', (req, res) => { // Pass dynamic data to the template const dynamicData = { pageTitle: 'My Node.js Dynamic Page', username: 'Guest', items: ['Learn Node.js', 'Master EJS', 'Build Cool Apps'] }; // Render the "index.ejs" template with our data res.render('index', dynamicData); }); // Start the server app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });Create Your EJS Template
Make a folder calledviews, then inside it createindex.ejs. This is where you’ll mix HTML and JavaScript, just like PHP:<!DOCTYPE html> <html> <head> <title><%= pageTitle %></title> </head> <body> <h1>Welcome, <%= username %>!</h1> <h2>Your To-Do List:</h2> <ul> <% items.forEach(item => { %> <li><%= item %></li> <% }) %> </ul> <% if (username === 'Admin') { %> <p>You have admin privileges!</p> <% } else { %> <p>You can upgrade to admin for more features.</p> <% } %> </body> </html>Notice the syntax:
<%= variable %>outputs the value (like<?php echo $variable; ?>)<% code %>runs JavaScript logic without outputting (like<?php // logic here ?>)
Run Your Server
Back in the terminal, run:node app.jsOpen your browser and go to
http://localhost:3000—you’ll see a fully dynamic page, just like you’d get with PHP!
Other Template Engines to Explore
If you want to try something different, here are a few popular options:
- Handlebars: Uses
{{ variable }}for output and helpers for logic, great for clean markup. - Pug (formerly Jade): Uses indentation instead of closing tags, more concise but has a steeper learning curve.
- Nunjucks: Similar to Handlebars but with more flexibility, supported by Mozilla.
Key Difference from PHP
Remember: In PHP, the server parses your .php files directly when a request comes in. In Node.js, your Express server first processes the request (runs any backend logic), then passes data to the template engine, which generates the final HTML to send back to the client. It’s a slightly different flow, but the end result is the same—dynamic, data-driven web pages.
Hope this helps you get started! Let me know if you hit any snags along the way.
内容的提问来源于stack exchange,提问作者AliAbbas Bhojani

