nodejsnotes

Topic 018: Display JSON in Nodejs

Topic 018: Display JSON in Nodejs

Displaying JSON using Node.js can be done in a few straightforward steps. Here’s a simple guide to help you get started.

This will cover setting up a basic Node.js server using the http module and sending a JSON response.

Write the Server Code: In server.js, add the following code to create a basic server that responds with JSON:

// Load the http module to create an HTTP server
const http = require("http");

// Define the port number
const port = 3000;

// Create the server
const server = http.createServer((req, res) => {
  // Set the response header to indicate the response is JSON
  res.setHeader("Content-Type", "application/json");

  // Define the JSON data
  const data = {
    message: "Hello, world!",
    timestamp: new Date().toISOString(),
  };

  // Send the JSON response
  res.end(JSON.stringify(data));
});

// Start the server
server.listen(port, () => {
  console.log(`Server running at http://localhost:${port}/`);
});

Explanation

Additional Tips

If you have JSON data stored in a file named example.json, you can read this file and send its contents as a response in your Node.js server. Here’s how you can do it:

Update the Server Code to Read the JSON File: In your server.js file, you will use Node.js’s built-in fs module to read the contents of example.json and then send it as a response.

Here’s how you can update your server.js:

const http = require("http");
const fs = require("fs");
const path = require("path");

const port = 3000;

const server = http.createServer((req, res) => {
  // Set the response header to indicate the response is JSON
  res.setHeader("Content-Type", "application/json");

  // Define the path to the JSON file
  const filePath = path.join(__dirname, "example.json");

  // Read the JSON file
  fs.readFile(filePath, "utf8", (err, data) => {
    if (err) {
      // Handle the error (e.g., file not found)
      res.statusCode = 500;
      res.end(JSON.stringify({ error: "Internal Server Error" }));
      console.error(err);
    } else {
      // Send the JSON file contents as the response
      res.end(data);
    }
  });
});

// Start the server
server.listen(port, () => {
  console.log(`Server running at http://localhost:${port}/`);
});

Explanation

USing Express JS

Create the Server Code: Create a new file named server.js and write the following code:

const express = require("express");
const fs = require("fs");
const path = require("path");

const app = express();
const port = 3000;

app.get("/", (req, res) => {
  // Define the path to the JSON file
  const filePath = path.join(__dirname, "example.json");

  // Read the JSON file
  fs.readFile(filePath, "utf8", (err, data) => {
    if (err) {
      // Handle the error (e.g., file not found)
      res.status(500).json({ error: "Internal Server Error" });
      console.error(err);
    } else {
      // Parse the JSON data and send it as the response
      res.json(JSON.parse(data));
    }
  });
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}/`);
});

Explanation

Additional Tips