Node.js quick file server (static files over HTTP)

前端 未结 30 2376
攒了一身酷
攒了一身酷 2020-11-22 12:30

Is there Node.js ready-to-use tool (installed with npm), that would help me expose folder content as file server over HTTP.

Example, if I have



        
30条回答
  •  忘掉有多难
    2020-11-22 13:06

    I haven't had much luck with any of the answers on this page, however, below seemed to do the trick.

    Add a server.js file with the following content:

    const express = require('express')
    const path = require('path')
    const port = process.env.PORT || 3000
    const app = express()
    
    // serve static assets normally
    app.use(express.static(__dirname + '/dist'))
    
    // handle every other route with index.html, which will contain
    // a script tag to your application's JavaScript file(s).
    app.get('*', function (request, response){
      response.sendFile(path.resolve(__dirname, 'dist', 'index.html'))
    })
    
    app.listen(port)
    console.log("server started on port " + port)
    

    Also make sure that you require express. Run yarn add express --save or npm install express --save depending on your setup (I can recommend yarn it's pretty fast).

    You may change dist to whatever folder you are serving your content is. For my simple project, I wasn't serving from any folder, so I simply removed the dist filename.

    Then you may run node server.js. As I had to upload my project to a Heroku server, I needed to add the following to my package.json file:

      "scripts": {
        "start": "node server.js"
      }
    

提交回复
热议问题