A lightweight, vanilla replacement for Express framework when parsing the HTTP body's data or parsing the URL parameters and queries with NodeJS.
Using npm:
$ npm install nodeparse
You first need to import the module.
const NodeParse = require("nodeparse");
Create a basic NodeJS http server, create nodeparse instance and use init()
method.
const http = require("http");
const NodeParse = require("nodeparse");
const port = process.env.PORT || 8080;
const server = http.createServer(function (req, res) {
const nodeparse = new NodeParse(req, res);
nodeparse.init();
});
server.listen(port, function (error) {
if (error) throw error;
console.log("Server is running on port ", port);
});
Using nodeparse.params
to get an array of params.
const server = http.createServer(function (req, res) {
const nodeparse = new NodeParse(req, res);
nodeparse.init();
if (req.method === "GET") {
console.log(nodeparse.params);
/*
https://localhost:3000/api/products
output: ["api", "products"]
*/
}
});
Using nodeparse.queries
to get an object of queries.
const server = http.createServer(function (req, res) {
const nodeparse = new NodeParse(req, res);
nodeparse.init();
if (req.method === "GET") {
console.log(nodeparse.queries);
/*
https://localhost:8080/api/products?name=banana&size=xl
output: {"name": "banana", "size": "xl"}
*/
}
});
Because nodeparse.data
is a promise return from req.on()
so you need to await
with nodeparse.init()
inside an async
function.
const server = http.createServer(async function (req, res) {
const nodeparse = new NodeParse(req, res);
await nodeparse.init();
if (req.method === "POST") {
console.log(nodeparse.data);
}
});
nodeparse is inspired by express when developers have to deal with params, queries and data with NodeJS.