DEV Community

Mosin Inamdar
Mosin Inamdar

Posted on

Give me some sample code in nodejs

Simple HTTP Server in Node.js

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

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

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. Import the http module: This module provides tools for creating and managing HTTP servers.
  2. Define hostname and port: These define where the server will listen for connections.
  3. Create a server: The http.createServer() function creates a new server instance.
  4. Define request handler: The function passed to createServer() handles incoming requests. It receives the req (request) and res (response) objects.
  5. Set response headers: res.statusCode sets the status code of the response (200 for success), and res.setHeader() adds custom headers.
  6. Send response body: res.end() sends the response body and ends the connection.
  7. Start the server: server.listen() starts the server and logs a message when it's ready.

To run this code:

  1. Save it as server.js.
  2. Open your terminal and navigate to the directory where you saved the file.
  3. Run node server.js.
  4. Open your web browser and visit http://127.0.0.1:3000/. You should see "Hello World" displayed.

Other Node.js Examples

1. Read a file:

const fs = require('fs');

fs.readFile('myfile.txt', 'utf8', (err, data) => {
  if (err) {
    console.error(err);
    return;
  }
  console.log(data);
});
Enter fullscreen mode Exit fullscreen mode

2. Create a directory:

const fs = require('fs');

fs.mkdir('new_directory', { recursive: true }, (err) => {
  if (err) {
    console.error(err);
    return;
  }
  console.log('Directory created successfully!');
});
Enter fullscreen mode Exit fullscreen mode

3. Use a module from npm:

const axios = require('axios');

axios.get('https://api.example.com/data')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });
Enter fullscreen mode Exit fullscreen mode

These are just simple examples. Node.js offers a vast ecosystem of modules and libraries for various tasks, including web development, data processing, and more. You can explore the documentation at https://nodejs.org/ to learn more.

Top comments (0)