Use Express to quickly build a static resource server

Sometimes, the client program implements certain functions and needs to be jointly debugged with the server, such as downloading some static resource files (XML, JSON, EXE, HTML/JS/CSS, etc.) from the server, like the scenario mentioned above: Testing Electron For the automatic upgrade function of the program, we introduced how to use Minio to build an S3 server without writing a single line of code.

What this article wants to introduce is that we can also use Express to quickly build a static resource download server with just a few lines of code.

 Proceed as follows:

1. Prerequisites, go to the official website to download and install the latest Node.js. After the installation is complete, execute node –v on the console to see if the installation is indeed successful

2. Create an empty folder (as a project folder) on the local hard disk, enter this folder from the console, and then execute the following command to forcibly create a simplified version of package.json:

npm init –y

3. Execute the following command to install Express:

npm install express

4. Create a main.js file in the project folder, and type in the following code (if you want to implement richer service functions, you can go to the Express Chinese website to view more sample codes ):

var express = require('express')
var path = require('path')
var serveStatic = require('serve-static')

const app = express()

const rootPath = path.join(__dirname, 'public')
app.use(serveStatic(rootPath))
app.listen(3000, ()=> {
    console.log('http://localhost:3000 started. Location: ' + rootPath)
})

5. Modify package.json to add the definition of start command:

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

6. Create a subfolder called public in the project folder, and then put an index.html file under public

7. Execute on the console: npm run start

8. Visit http://127.0.0.1:3000/index.html in the browser , if the page is successfully opened, congratulations, the server is successfully built!

Git complete demo code:
https://github.com/luqiming666/ExpressServer-static

Guess you like

Origin blog.csdn.net/happydeer/article/details/122893161