servscript v2.3.15
ServScript
ServScript
is a lightweight and configurable Node.js server navigation module designed to handle HTTP requests and serve static files efficiently.
Features
- Simple configuration: Easily set up your server with customizable options.
- File serving: Serve static files from a specified directory.
- Creating routes: Helps to create routes conveniently.
- Custom Pages: Define custom routes and associated files.
- Main page and 404 handling: Specify main page and custom 404 error page.
- Advanced callbacks: Use advanced and error callbacks for custom behavior.
- Referer logging: Log the referer URL to track request sources.
- Free port finder: Automatically find a free port to run the server using portfinder.
Installation
To install ServScript
, use npm:
npm install servscript
Usage
Here's a basic example of how to use ServScript
in your project:
import { Routing, Routes } from 'servscript';
// Define your pages and other configuration options
const pages = new Routes()
.set(['pages', 'about.html'])
.set(['pages', 'contact.html'])
.getAll();
const mainPage = 'pages/index.html';
const notFoundPage = 'pages/404.html';
const pathToServer = '../../..'; // Project directory
// Create a new Routing instance
const server = new Routing(pages, mainPage, notFoundPage, pathToServer);
// Start the server
server.start(3000, 'localhost', () => {
console.log('Server is running on http://localhost:3000');
});
Import
You can import the module as follows:
import { Routing, Routes } from 'servscript';
API
Routing
constructor(pages, pagesDirectory, mainPage, notFoundPage, pathToServer, relative, port, host, advCallback, errorCallback)
Creates a new Routing instance.
pages
: An object where keys are route names and values are the filenames of the associated pages.mainPage
: The main page of your application (e.g.,index.html
).notFoundPage
: The custom 404 error page (e.g.,404.html
).pathToServer
: (Optional) The server directory (default:'../../..'
).relative
: (Optional) Iftrue
, paths are resolved relative to the source (default:true
).port
: (Optional) The port on which the server will run (default:3000
).host
: (Optional) The host on which the server will run (default:'localhost'
).advCallback
: (Optional) A custom advanced callback function.errorCallback
: (Optional) A custom error callback function.
Advanced Callback
The advCallback
function allows for custom behavior during the request processing. This function receives an object with the following properties:
request
: The HTTP request object.response
: The HTTP response object.address(url, callback)
: Executes the callback if the request URL matches.stop()
: Ends the response without further processing.redirect(url)
: Redirects to the specified URL.send(path)
: Sends the specified file or imitated content.imitate(content, type)
: Returns an object representing imitated content.status(code)
: Sets the response status code.url
: The request URL.resolvePath(file)
: Resolves the file path relative to the server's directory.path
: The resolved file path.source
: The referer URL path.query
: The query parameters of the request URL.
Example usage of advCallback
:
advCallback: async (actions) => {
actions.address('/custom', async () => {
actions.send(await actions.resolvePath('pages/custom.html'));
});
}
Error Callback
The errorCallback
function is used to handle errors that occur during request processing. This function receives the following parameters:
e
: The error object.req
: The HTTP request object.res
: The HTTP response object.
Example usage of errorCallback
:
errorCallback: (e, req, res) => {
console.error(e);
res.writeHead(500, {'Content-Type': 'text/plain'});
res.end(`Server Error: ${e.message}`);
}
start(port, host, callback)
Starts the server.
port
: (Optional) The port on which the server will run (default:this.port
).host
: (Optional) The host on which the server will run (default:this.host
).callback
: (Optional) A callback function to execute after the server starts.
Example:
server.start(3000, 'localhost', () => {
console.log('Server is running on http://localhost:3000');
});
stop(callback)
Stops the server.
callback
: (Optional) A callback function to execute after the server stops.
Example:
server.stop(() => {
console.log('Server has been stopped');
});
set(params)
Sets server parameters.
params
: An object with keys corresponding to server parameters.
Example:
server.set({
host: '127.0.0.1',
port: 8080
});
getPathByUrl(url)
Gets the path of a file based on the URL.
url
: The URL from which to determine the file path.
Returns the resolved file path.
Example:
const path = server.getPathByUrl('/about');
console.log(path); // Output: Full path to 'about.html'
static createPath(path)
Creates a path from an array of path segments.
path
: An array of path segments.
Example:
const fullPath = Routing.createPath(['users', '123', 'profile']);
console.log(fullPath); // Output: 'users/123/profile'
static async getFreePort()
Asynchronously finds and returns a free port using portfinder.
Returns a free port as a number.
Example:
const freePort = await Routing.getFreePort();
console.log(`Free port found: ${freePort}`);
Routes
constructor()
Creates a new Routes instance.
getAll()
Returns all routes.
set(path, name)
Creates or rewrites a route.
path
: Relative path to the file.name
: (Optional) The URL of this route.
Returns the updated Routes instance.
Example:
const routes = new Routes()
.set(['pages', 'about.html'])
.set(['pages', 'contact.html'])
.set(['pages', 'index.html'], 'main')
.getAll();
console.log(routes); // Output: {about: 'pages/about.html', contact: 'pages/contact.html', main: 'index.html'}
getPath(name)
Returns the route path by name as an array.
name
: Route name.
Example:
const mainRoutePath = new Routes()
.set(['pages', 'about.html'])
.set(['pages', 'contact.html'])
.set(['pages', 'index.html'], 'main')
.getPath('main');
console.log(mainRoutePath); // Output: ['pages', 'index.html']
getNames(path)
Returns route names by file path.
Example:
const aboutRouteNames = new Routes()
.set(['pages', 'about.html'])
.set(['pages', 'about.html'], 'info')
.set(['pages', 'contact.html'])
.set(['pages', 'index.html'], 'main')
.getNames(['pages', 'about.html']);
console.log(aboutRouteNames); // Output: ['about', 'info']
remove(name)
Removes a route by name.
name
: Route name.
Returns the updated Routes instance.
Example:
const removedInfo = new Routes()
.set(['pages', 'about.html'])
.set(['pages', 'about.html'], 'info')
.set(['pages', 'contact.html'])
.set(['pages', 'index.html'], 'main')
.remove('info')
.getAll();
console.log(removedInfo); // Output: {about: 'pages/about.html', contact: 'pages/contact.html', main: 'pages/index.html'}
clear
Removes all routes.
Returns the updated Routes instance.
Example:
const removedAll = new Routes()
.set(['pages', 'about.html'])
.set(['pages', 'about.html'], 'info')
.set(['pages', 'contact.html'])
.set(['pages', 'index.html'], 'main')
.clear()
.getAll();
console.log(removedAll); // Output: {}
When to use
ServScript
is particularly useful in the following scenarios:
Development Server:
- Quickly set up a local development server to serve your static HTML, CSS, and JavaScript files.
Static Site Hosting:
- Easily host static files or websites over HTTP.
Custom Routing:
- Define custom routes and associate them with specific files.
Single Page Applications (SPA):
- Serve the main HTML file and handle 404 errors with a custom error page.
File Serving:
- Serve various file types.
Custom Server Behavior:
- Use advanced and error callbacks for custom behavior and error handling.
Running Tests
To run tests, you can simply use the following command:
npm test
Make sure you have a test script defined in your package.json
and a test file created with your test cases.
License
This project is licensed under the MIT License.
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago