Summary of several methods of building local file server with nodeJS

  • 2021-08-03 09:10:19
  • OfStack

To build an nodejs server:

1. Install nodejs service, node equivalent to apache server

2. Create a new server file in your own directory, such as server. js

For example, I created the server. js file under E:\ PhpProject\ HTML5\ websocket


var http = require('http');// Introduce http Module 

// Start the service and listen 8888 Port 
// The port number is preferably 6000 Above 
var server = http.createServer(function(req,res){
  /*
    req Used to accept client data 
    res Used to send server data to the client 
  */

  console.log(' There is a client connection ');// Successful connection creation is displayed in the background 

  //1 Reference is http Request status, 200 Connection succeeded 
  // Write header information to the client after successful connection 
  res.writeHeader(200,{
    'content-type' : 'text/html;charset="utf-8"'
  });

  res.write(' This is the body part ');// Show to Client 
  res.end();

}).listen(8888);

console.log(' Server started successfully ');

3. Switch cd to the directory where server. js is located in the cmd console, and then execute the node server. js command

When the console displays "Server started successfully", it means that the node server has been established

4. Access the server in a browser

Enter in the browser

localhost: 8888, and the browser displays "This is the body part".

Look at the cmd console and show "There is a client connection"

The above operations can be performed in multiple browser windows, and each browser window will correspond to "Client Connection" once

The above steps are completed, and the node service is built. Here is how to access the text/html text file for the local site through the node service you set up

Access local site files

1. Create the node service file server2. js in a custom directory


var http = require('http');
var fs = require('fs');// Introducing file reading module 

var documentRoot = 'E:/PhpProject/html5/websocket/www';
// The directory where the files to be accessed are stored 

var server= http.createServer(function(req,res){

  var url = req.url; 
  // Client-entered url For example, if you enter localhost:8888/index.html
  // So here's url == /index.html 

  var file = documentRoot + url;
  console.log(url);
  //E:/PhpProject/html5/websocket/www/index.html 


  fs.readFile( file , function(err,data){
  /*
    1 Refer to file path 
    2 Parameters are callback functions 
       Callback function's 1 Read the information returned by the error. If you return null, there will be no error 
      2 Refer to the text content returned after reading successfully 
  */
    if(err){
      res.writeHeader(404,{
        'content-type' : 'text/html;charset="utf-8"'
      });
      res.write('<h1>404 Errors </h1><p> The page you are looking for does not exist </p>');
      res.end();
    }else{
      res.writeHeader(200,{
        'content-type' : 'text/html;charset="utf-8"'
      });
      res.write(data);// Will index.html Display on the client 
      res.end();

    }

  });



}).listen(8888);

console.log(' Server started successfully ');

2. Create the index. html file

If you want to access the index. html file, of course, you must have this file first, otherwise the server fails to read it and returns 404

3. Execute the command node server2.js under the directory where server switches to server2.js in the cmd console

Start the server

4. Enter localhost: 8888/index. html in the browser to access the file

If the computer does not install nodejs students can first go to node official download and install node program.

After installing nodejs, verify whether the installation is successful under 1! If it appears, it indicates that node has been installed!

After installing node, open cmd, enter npm, install, anywhere-g, install anywhere, and wait until the following interface appears.

After the above two steps are in place, everything is ready, only the east wind is needed! Find the path you want to build the server on the cmd page, and then enter anywhere 8860 under the current path

Then the browser automatically opens the local access URL, and a simple node server is built by us!

END

Matters needing attention

anywhere recommends installing the global node recommends 32-bit, 64-bit compatibility is not as good as 32-bit at present

If we open the html file directly, it is opened in file://, but this way sometimes encounters cross-domain problems: "cross-origin", so we need to build a simple local server, and Nodejs can meet our needs:

For example, my local server js file is like this (I put this server. js in the Nodejs installation directory):


var connect = require("connect");
var serveStatic = require("serve-static");

var app = connect();
app.use(serveStatic("C:\\xxx\\xxx\\xxx\\ Project Folder "));

app.listen(5000);

To run, just execute: node server. js

After normal operation, we can enter localhost: 5000 in the browser to access the files in the project folder. (If it is index. html file can be omitted, this file is loaded by default.)


Related articles: