How to use the createServer function from http-server

Find comprehensive JavaScript http-server.createServer code examples handpicked from public code repositorys.

http-server.createServer is a function that creates a basic HTTP server for serving static files and directories over the web.

949
950
951
952
953
954
955
956
957
958
    index.join('\n')
  );
});


gulp.task('simpleserver', ['generate-test-samples'], function(cb) {
  httpServer.createServer({ root: '../', cache: 5 }).listen(8080);
  httpServer.createServer({ root: '../', cache: 5 }).listen(8088);
  console.log('LISTENING on 8080 and 8088');
});
fork icon0
star icon0
watch icon1

+ 29 other calls in file

How does http-server.createServer work?

http-server.createServer is a function provided by the http-server library that creates a simple HTTP server for serving static files and directories over the web.

When http-server.createServer is called, it takes an optional configuration object that can be used to customize various aspects of the server's behavior, such as the port number or the root directory to serve files from.

Once the server is created, it listens for incoming HTTP requests and responds to them by serving files or directories from the specified root directory.

The http-server library uses the http module built into Node.js to create the server, and provides various options for customizing its behavior, such as enabling HTTPS, setting caching policies, and logging server events.

By providing a simple way to create an HTTP server for serving static files and directories, http-server.createServer enables developers to quickly and easily set up a basic web server for testing, development, or production use.

Ai Example

1
2
3
4
5
6
7
8
9
10
const httpServer = require("http-server");

const server = httpServer.createServer({
  root: "./public",
  port: 8080,
});

server.listen(() => {
  console.log(`Server running on http://localhost:${server.address().port}`);
});

In this example, we import the http-server library and use httpServer.createServer to create a new HTTP server. We pass an options object to httpServer.createServer that specifies the root directory to serve files from (./public) and the port number to listen on (8080). The resulting server object represents the HTTP server, which we start by calling its listen method. This method takes an optional callback function that is called once the server is listening. In this case, we use the callback to log a message to the console indicating that the server is running, along with its address and port number. Once the server is running, it will serve files from the ./public directory to any clients that connect to it over HTTP.