JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network

How do I use Node.js for server-side JavaScript?

Asked on Sep 18, 2024

Answer

Node.js allows you to run JavaScript on the server side, enabling you to build scalable network applications. Here's a simple example of creating a basic HTTP server using Node.js.
<!-- BEGIN COPY / PASTE -->
        const http = require('http');

        const server = http.createServer((req, res) => {
            res.statusCode = 200;
            res.setHeader('Content-Type', 'text/plain');
            res.end('Hello, World!\n');
        });

        const PORT = 3000;
        server.listen(PORT, () => {
            console.log(`Server running at http://localhost:${PORT}/`);
        });
        <!-- END COPY / PASTE -->
Additional Comment:
  • This code creates an HTTP server using Node.js's built-in "http" module.
  • The server listens on port 3000 and responds with "Hello, World!" to any incoming requests.
  • To run this server, save the code to a file (e.g., "server.js") and execute it using the command "node server.js" in your terminal.
  • Ensure Node.js is installed on your system to execute the code.
✅ Answered with JavaScript best practices.
← Back to All Questions