0

I tried looking for information regarding this but everything includes Express JS which I cannot use for this task. I need to display index.html with pictures and an external CSS file called styles.css. I am successful in displaying the HTML. For the pictures I also tried using "<img class="logo" src="http://localhost:8888/pic.png" alt="My_Logo" />" This also does not work.

Here is my JS code.

var http = require("http"); 
var fs = require('fs');

function onRequest(request,response){
    response.writeHead(200,{'Content-Type':'text/html'});
    fs.readFile('./index.html',null,function(error,data){
        if(error){
            response.writeHead(404);
            response.write('File not found');
        }else{
            response.write(data);
        }
        response.end();
    });
}
http.createServer(onRequest).listen(8000);

Here is my HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Project 2</title>
    <link rel="stylesheet" href="styles.css" />
  </head>

  <body>
    <img class="logo" src="http://localhost:8888/pic.png" alt="My_Logo" />
    <div class="head">
      <h1>Social Media Network</h1>
    </div>
    <div class="startHeader">
        <img src="pic1.png" class="bottompic" alt="" />
        <h2>Start Your Network Today</h2>
    </div>
  </body>
</html>

EDIT: Im going to try this out : Node.js - external JS and CSS files (just using node.js not express)

2
  • 1
    You have to implement routing. Read the request url and method and send a corresponding response, e.g. if (request.url === '/styles.css') { /* send CSS */ } else { /* send HTML */ } Commented Dec 2, 2021 at 15:28
  • use what's in request to determine if it's a request for not index.html, load and serve file accordingly Commented Dec 2, 2021 at 15:28

1 Answer 1

0

If you want to serve static files like CSS and pictures using Node.js without using Express.js, you can use the built-in http module along with fs (File System) module.

const http = require('http');
const fs = require('fs');
const path = require('path');
const url = require('url');

const server = http.createServer((req, res) => {
  // Parse the requested URL
  const parsedUrl = url.parse(req.url, true);

  // Get the pathname from the URL
  const pathname = parsedUrl.pathname;

  // Set the content type based on the file extension
  const contentType = getContentType(pathname);

  // Map the requested URL to the corresponding file path
  const filePath = path.join(__dirname, 'public', pathname);

  // Read the file from the file system
  fs.readFile(filePath, (err, data) => {
    if (err) {
      // If the file is not found, send a 404 response
      res.writeHead(404, { 'Content-Type': 'text/plain' });
      res.end('File not found');
    } else {
      // If the file is found, send the file content with the appropriate content type
      res.writeHead(200, { 'Content-Type': contentType });
      res.end(data);
    }
  });
});

// Function to determine the content type based on the file extension
function getContentType(filePath) {
  const extname = path.extname(filePath);
  switch (extname) {
    case '.html':
      return 'text/html';
    case '.css':
      return 'text/css';
    case '.js':
      return 'text/javascript';
    case '.jpg':
    case '.jpeg':
      return 'image/jpeg';
    case '.png':
      return 'image/png';
    case '.gif':
      return 'image/gif';
    default:
      return 'application/octet-stream';
  }
}

const port = process.env.PORT || 3000;

server.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.