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

var ROOT ='./view/index.html';

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    fs.readFile(ROOT, function (err,data){
      if (err) {
        res.writeHead(404);
        res.end(JSON.stringify(err));
        return;
      }
      res.end(data);
    });
}).listen(8080);

This is common create server code for node.js - it's simple for npm start

I wonder that how I use .js file in browser (npm start)

I thought the fs can't read the details of <script src='...'></script>

RobC
  • 22,977
  • 20
  • 73
  • 80
황정욱
  • 11
  • 3

2 Answers2

0

Currently, your node.js app just knows how to serve one file, at ./view/index.html. You need it to be able to serve different files depending on the request - for example, initially it should serve an HTML file, and then a JS file since your HTML file will have a <script> tag referencing a JS file. While you wouldn't want the following example in a production environment, I am trying to keep it simple for the sake of example:

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

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': req.url.endsWith('html') ? 'text/html' : 'application/javascript'});    
    fs.readFile(path.join(__dirname, req.url), function (err,data){
      if (err) {
        res.writeHead(404);
        res.end(JSON.stringify(err));
        return;
      }
      res.end(data);
    });
}).listen(8080);

Now imagine that you have index.html in the same directory as your Node.js script:

<!DOCTYPE html>
<html>
<head></head>
<body>
    <p>Hello, world!</p>
<script src="./hello.js"></script>
</body>
</html>

As you can see, it references a JS script, hello.js. This is going to be in the same directory as well.

// hello.js 

alert('hello, world!');

Now, assuming your HTML file is named index.html, you can access it at localhost:8080/index.html, and it will also load your hello.js script.

nb1987
  • 1,400
  • 1
  • 11
  • 12
0

Right now all you're doing is getting the server to respond with the contents of the file in ROOT. So any requests that are sent, regardless of the path, will get the ROOT file instead.

Instead, you should make your handler produce the requested file:

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

var ROOT ='./view/index.html';

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    if (req.url=="/")req.url="/index.html";
    fs.readFile("./view"+req.url, function (err,data){
      if (err) {
        res.writeHead(404);
        res.end(JSON.stringify(err));
        return;
      }
      res.end(data);
    });
}).listen(8080);

Sorry this is a bit hacked together - I'm new to node as well. But I hope it helps!

acenturyandabit
  • 1,188
  • 10
  • 24