Hello, World!
This is my first Node.js application.
'); }); // Define the port to listen on const PORT = 3000; server.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); }); ``` --- ### 6. Run the Server Start your application by running the start script in your terminal: ```bash npm start ``` You should see the following output in your console: ```text Server is running on http://localhost:3000 ``` --- ### 7. Test the Application Open your web browser and navigate to `http://localhost:3000`. You should see your HTML message displayed on the page: ```text Hello, World! This is my first Node.js application. ``` --- ### 8. Add Basic Routing To make your application more interactive, you can inspect the request URL (`req.url`) and implement basic routing. Update your `app.js` file with the following code: ```javascript const http = require('http'); const server = http.createServer((req, res) => { // Route: Homepage if (req.url === '/') { res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); res.end('Welcome to the homepage!'); } // Route: About Page else if (req.url === '/about') { res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); res.end('This is the about page.'); } // Route: 404 Not Found else { res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' }); res.end('404 Not Found'); } }); const PORT = 3000; server.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); }); ``` Restart your server (press `Ctrl + C` to stop it, then run `npm start` again) and test the different paths: * `http://localhost:3000/` -> Displays "Welcome to the homepage!" * `http://localhost:3000/about` -> Displays "This is the about page." * `http://localhost:3000/anything-else` -> Displays "404 Not Found" --- ### Considerations & Next Steps * **Development Workflow:** Manually restarting the server after every code change can be tedious. Consider installing `nodemon` (`npm install --save-dev nodemon`) to automatically restart your server when files change. * **Production Readiness:** The built-in `http` module is excellent for understanding Node.js fundamentals. However, for larger production applications, developers typically use robust web frameworks like **Express**, **Fastify**, or **NestJS** to handle complex routing, middleware, and security. * **Scalability:** This basic setup can easily be extended by connecting to databases (such as MongoDB or PostgreSQL) and implementing RESTful APIs.
YouTip