How to link css file in node.js











up vote
1
down vote

favorite












I am new to node.js and js in general. I have a simple app that have a styles.css but I dont know how to link it on the app.js.



In the index.html it has <link rel="stylesheet" type="text/css" href="css/styles.css">



And this is my app.js for the node.js:



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

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


fs.readFile('index.html', (err, html) =>{
if (err){
throw err;
}
const server = http.createServer((req,res) => {
res.statusCode = 200;
res.setHeader('Content-type', 'text/html');
res.write(html);
res.end();

});

server.listen(port, hostname, () => {
console.log('Server started on port ' + port);
});
});


So how should I modify app.js so that it will be able to locate the css file?










share|improve this question


















  • 1




    Your request handler always responds with the contents of your index.html. So when the browser parses the html, it then requests css/styles.css which your server responds by sending it the index.html again. You should distinguish between requests for index.html and css/styles.css to return content accordingly.
    – shkaper
    Nov 11 at 22:22










  • import "path to CSS file";
    – Fox
    Nov 11 at 22:25






  • 1




    Are you familiar with Express.js or is it a requirement to use raw Node.js without any frameworks?
    – SakoBu
    Nov 11 at 22:28















up vote
1
down vote

favorite












I am new to node.js and js in general. I have a simple app that have a styles.css but I dont know how to link it on the app.js.



In the index.html it has <link rel="stylesheet" type="text/css" href="css/styles.css">



And this is my app.js for the node.js:



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

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


fs.readFile('index.html', (err, html) =>{
if (err){
throw err;
}
const server = http.createServer((req,res) => {
res.statusCode = 200;
res.setHeader('Content-type', 'text/html');
res.write(html);
res.end();

});

server.listen(port, hostname, () => {
console.log('Server started on port ' + port);
});
});


So how should I modify app.js so that it will be able to locate the css file?










share|improve this question


















  • 1




    Your request handler always responds with the contents of your index.html. So when the browser parses the html, it then requests css/styles.css which your server responds by sending it the index.html again. You should distinguish between requests for index.html and css/styles.css to return content accordingly.
    – shkaper
    Nov 11 at 22:22










  • import "path to CSS file";
    – Fox
    Nov 11 at 22:25






  • 1




    Are you familiar with Express.js or is it a requirement to use raw Node.js without any frameworks?
    – SakoBu
    Nov 11 at 22:28













up vote
1
down vote

favorite









up vote
1
down vote

favorite











I am new to node.js and js in general. I have a simple app that have a styles.css but I dont know how to link it on the app.js.



In the index.html it has <link rel="stylesheet" type="text/css" href="css/styles.css">



And this is my app.js for the node.js:



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

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


fs.readFile('index.html', (err, html) =>{
if (err){
throw err;
}
const server = http.createServer((req,res) => {
res.statusCode = 200;
res.setHeader('Content-type', 'text/html');
res.write(html);
res.end();

});

server.listen(port, hostname, () => {
console.log('Server started on port ' + port);
});
});


So how should I modify app.js so that it will be able to locate the css file?










share|improve this question













I am new to node.js and js in general. I have a simple app that have a styles.css but I dont know how to link it on the app.js.



In the index.html it has <link rel="stylesheet" type="text/css" href="css/styles.css">



And this is my app.js for the node.js:



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

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


fs.readFile('index.html', (err, html) =>{
if (err){
throw err;
}
const server = http.createServer((req,res) => {
res.statusCode = 200;
res.setHeader('Content-type', 'text/html');
res.write(html);
res.end();

});

server.listen(port, hostname, () => {
console.log('Server started on port ' + port);
});
});


So how should I modify app.js so that it will be able to locate the css file?







javascript html css






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 11 at 22:08









Jiajun Yang

5423724




5423724








  • 1




    Your request handler always responds with the contents of your index.html. So when the browser parses the html, it then requests css/styles.css which your server responds by sending it the index.html again. You should distinguish between requests for index.html and css/styles.css to return content accordingly.
    – shkaper
    Nov 11 at 22:22










  • import "path to CSS file";
    – Fox
    Nov 11 at 22:25






  • 1




    Are you familiar with Express.js or is it a requirement to use raw Node.js without any frameworks?
    – SakoBu
    Nov 11 at 22:28














  • 1




    Your request handler always responds with the contents of your index.html. So when the browser parses the html, it then requests css/styles.css which your server responds by sending it the index.html again. You should distinguish between requests for index.html and css/styles.css to return content accordingly.
    – shkaper
    Nov 11 at 22:22










  • import "path to CSS file";
    – Fox
    Nov 11 at 22:25






  • 1




    Are you familiar with Express.js or is it a requirement to use raw Node.js without any frameworks?
    – SakoBu
    Nov 11 at 22:28








1




1




Your request handler always responds with the contents of your index.html. So when the browser parses the html, it then requests css/styles.css which your server responds by sending it the index.html again. You should distinguish between requests for index.html and css/styles.css to return content accordingly.
– shkaper
Nov 11 at 22:22




Your request handler always responds with the contents of your index.html. So when the browser parses the html, it then requests css/styles.css which your server responds by sending it the index.html again. You should distinguish between requests for index.html and css/styles.css to return content accordingly.
– shkaper
Nov 11 at 22:22












import "path to CSS file";
– Fox
Nov 11 at 22:25




import "path to CSS file";
– Fox
Nov 11 at 22:25




1




1




Are you familiar with Express.js or is it a requirement to use raw Node.js without any frameworks?
– SakoBu
Nov 11 at 22:28




Are you familiar with Express.js or is it a requirement to use raw Node.js without any frameworks?
– SakoBu
Nov 11 at 22:28












2 Answers
2






active

oldest

votes

















up vote
1
down vote













for every request you are returning index.html.



Try this:



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

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


fs.readFile('index.html', (err, html) =>{
if (err){
throw err;
}
const server = http.createServer((req,res) => {


res.statusCode = 200;
if(req.url == '/'){
res.setHeader('Content-type', 'text/html');
res.write(html);
res.end();
res.statusCode = 200;
}

else if(req.url == '/css/styles.css'){
res.setHeader('Content-type', 'text/css');
res.write(fs.readFileSync('css/styles.css'));
res.end();
} else {
res.write("invalid request")
res.end();
}

});

server.listen(port, hostname, () => {
console.log('Server started on port ' + port);
});
});





share|improve this answer




























    up vote
    1
    down vote













    If you're not limited to raw node.js and can use express.js here is what you can do to serve static files



    Here is your server.js



    const express = require("express");
    const app = express();

    app.use(express.static("public"));

    const PORT = process.env.PORT || 8080;

    app.listen(PORT, () => {
    console.log(`Your app is listening on port ${PORT}`);
    });


    Then you create a folder and call it public and that's where all your client-side goes...



    Here is an live demo for a complete working example: https://glitch.com/edit/#!/peridot-wildcat?path=README.md:1:0






    share|improve this answer





















      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53253739%2fhow-to-link-css-file-in-node-js%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      1
      down vote













      for every request you are returning index.html.



      Try this:



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

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


      fs.readFile('index.html', (err, html) =>{
      if (err){
      throw err;
      }
      const server = http.createServer((req,res) => {


      res.statusCode = 200;
      if(req.url == '/'){
      res.setHeader('Content-type', 'text/html');
      res.write(html);
      res.end();
      res.statusCode = 200;
      }

      else if(req.url == '/css/styles.css'){
      res.setHeader('Content-type', 'text/css');
      res.write(fs.readFileSync('css/styles.css'));
      res.end();
      } else {
      res.write("invalid request")
      res.end();
      }

      });

      server.listen(port, hostname, () => {
      console.log('Server started on port ' + port);
      });
      });





      share|improve this answer

























        up vote
        1
        down vote













        for every request you are returning index.html.



        Try this:



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

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


        fs.readFile('index.html', (err, html) =>{
        if (err){
        throw err;
        }
        const server = http.createServer((req,res) => {


        res.statusCode = 200;
        if(req.url == '/'){
        res.setHeader('Content-type', 'text/html');
        res.write(html);
        res.end();
        res.statusCode = 200;
        }

        else if(req.url == '/css/styles.css'){
        res.setHeader('Content-type', 'text/css');
        res.write(fs.readFileSync('css/styles.css'));
        res.end();
        } else {
        res.write("invalid request")
        res.end();
        }

        });

        server.listen(port, hostname, () => {
        console.log('Server started on port ' + port);
        });
        });





        share|improve this answer























          up vote
          1
          down vote










          up vote
          1
          down vote









          for every request you are returning index.html.



          Try this:



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

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


          fs.readFile('index.html', (err, html) =>{
          if (err){
          throw err;
          }
          const server = http.createServer((req,res) => {


          res.statusCode = 200;
          if(req.url == '/'){
          res.setHeader('Content-type', 'text/html');
          res.write(html);
          res.end();
          res.statusCode = 200;
          }

          else if(req.url == '/css/styles.css'){
          res.setHeader('Content-type', 'text/css');
          res.write(fs.readFileSync('css/styles.css'));
          res.end();
          } else {
          res.write("invalid request")
          res.end();
          }

          });

          server.listen(port, hostname, () => {
          console.log('Server started on port ' + port);
          });
          });





          share|improve this answer












          for every request you are returning index.html.



          Try this:



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

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


          fs.readFile('index.html', (err, html) =>{
          if (err){
          throw err;
          }
          const server = http.createServer((req,res) => {


          res.statusCode = 200;
          if(req.url == '/'){
          res.setHeader('Content-type', 'text/html');
          res.write(html);
          res.end();
          res.statusCode = 200;
          }

          else if(req.url == '/css/styles.css'){
          res.setHeader('Content-type', 'text/css');
          res.write(fs.readFileSync('css/styles.css'));
          res.end();
          } else {
          res.write("invalid request")
          res.end();
          }

          });

          server.listen(port, hostname, () => {
          console.log('Server started on port ' + port);
          });
          });






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 11 at 22:29









          Aagam Jain

          1,2861417




          1,2861417
























              up vote
              1
              down vote













              If you're not limited to raw node.js and can use express.js here is what you can do to serve static files



              Here is your server.js



              const express = require("express");
              const app = express();

              app.use(express.static("public"));

              const PORT = process.env.PORT || 8080;

              app.listen(PORT, () => {
              console.log(`Your app is listening on port ${PORT}`);
              });


              Then you create a folder and call it public and that's where all your client-side goes...



              Here is an live demo for a complete working example: https://glitch.com/edit/#!/peridot-wildcat?path=README.md:1:0






              share|improve this answer

























                up vote
                1
                down vote













                If you're not limited to raw node.js and can use express.js here is what you can do to serve static files



                Here is your server.js



                const express = require("express");
                const app = express();

                app.use(express.static("public"));

                const PORT = process.env.PORT || 8080;

                app.listen(PORT, () => {
                console.log(`Your app is listening on port ${PORT}`);
                });


                Then you create a folder and call it public and that's where all your client-side goes...



                Here is an live demo for a complete working example: https://glitch.com/edit/#!/peridot-wildcat?path=README.md:1:0






                share|improve this answer























                  up vote
                  1
                  down vote










                  up vote
                  1
                  down vote









                  If you're not limited to raw node.js and can use express.js here is what you can do to serve static files



                  Here is your server.js



                  const express = require("express");
                  const app = express();

                  app.use(express.static("public"));

                  const PORT = process.env.PORT || 8080;

                  app.listen(PORT, () => {
                  console.log(`Your app is listening on port ${PORT}`);
                  });


                  Then you create a folder and call it public and that's where all your client-side goes...



                  Here is an live demo for a complete working example: https://glitch.com/edit/#!/peridot-wildcat?path=README.md:1:0






                  share|improve this answer












                  If you're not limited to raw node.js and can use express.js here is what you can do to serve static files



                  Here is your server.js



                  const express = require("express");
                  const app = express();

                  app.use(express.static("public"));

                  const PORT = process.env.PORT || 8080;

                  app.listen(PORT, () => {
                  console.log(`Your app is listening on port ${PORT}`);
                  });


                  Then you create a folder and call it public and that's where all your client-side goes...



                  Here is an live demo for a complete working example: https://glitch.com/edit/#!/peridot-wildcat?path=README.md:1:0







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 11 at 22:35









                  SakoBu

                  788317




                  788317






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53253739%2fhow-to-link-css-file-in-node-js%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Guess what letter conforming each word

                      Port of Spain

                      Run scheduled task as local user group (not BUILTIN)