Sponge
Sponge

Reputation: 33

fs readFile working in console but not in server Node.js

I want to show the content of my index.html file in my webpage

Here is my code in server.js

  var express = require('express')()
const fs = require('fs');

express.get('/', (request, reponse) => {

    const path = './index.html';

    console.log(path);

    if (fs.existsSync(path)) {
        fs.readFile('./index.html', "utf8", (err, data) => {
            if (err) {
                console.log(err);
            }
            console.log(data);
        })
    }
    else {
        console.log('nope');
    }

This code shows my html file content in my console, however it doesn't in my server. The page doesn't stop loading.

EDIT

I wasn't returning my data, I added reponse.send(data) and it works perfectly.

Upvotes: 0

Views: 250

Answers (1)

Chirag Bansal
Chirag Bansal

Reputation: 84

Just use res.sendFile method to return the html page, you actually don't need to use fs in this scenario.

Example:

router.get('/', (req,res) => {
   res.sendFile('home.html');
});

Upvotes: 1

Related Questions