Basic static file server in NodeJS

后端 未结 8 766
盖世英雄少女心
盖世英雄少女心 2020-11-28 20:06

I\'m trying to create a static file server in nodejs more as an exercise to understand node than as a perfect server. I\'m well aware of projects like Connect and node-stati

8条回答
  •  情深已故
    2020-11-28 20:17

    Less is more

    Just go command prompt first on your project and use

    $ npm install express
    

    Then write your app.js code like so:

    var express = require('express'),
    app = express(),
    port = process.env.PORT || 4000;
    
    app.use(express.static(__dirname + '/public'));
    app.listen(port);
    

    You would then create a "public" folder where you place your files. I tried it the harder way first but you have to worry about mime types which is just having to map stuff which is time consuming and then worry about response types, etc. etc. etc.... no thank you.

提交回复
热议问题