Node itself can serve static files without express or any other module..?

前端 未结 5 2278
眼角桃花
眼角桃花 2021-02-20 06:28

I am beginner in the field of node js.No idea how to send simple request from url Like :- http://localhost:9999/xyz/inde.html my file hierarchy is

server.js
xyz         


        
5条回答
  •  耶瑟儿~
    2021-02-20 06:43

    It's ridiculous to attempt to create a node application without npm dependencies, because the base of nodejs is just that -- a base. Unless you feel like implementing entire protocols, you're better off using a minimal, well maintained npm module that does that for you. That said, here is the very basic thing you asked for (without MiME, eTags, caching, etc, etc):

    var basePath = __dirname;
    var http = require('http');
    var fs = require('fs');
    var path = require('path');
    
    http.createServer(function(req, res) {
        var stream = fs.createReadStream(path.join(basePath, req.url));
        stream.on('error', function() {
            res.writeHead(404);
            res.end();
        });
        stream.pipe(res);
    }).listen(9999);
    

提交回复
热议问题