📜 ⬆️ ⬇️

Lightweight module for HTTP requests

It all started when I faced the task of writing a bot for Telegram, here, for the first time, I ran into their API . To work with him, I chose the currently popular Request module.

Bot was written. I noticed that their memory consumption grew with each request to the API, having caught a ponderous Request in the problem, I decided to try to write my own module for HTTP requests, as simple as possible, lightweight and fast.


')
As a result, the most compact one came out (now in the main module file there are less than 200 lines) and a module that is not deprived of functionality, which I called tiny_request.

Ease of use


For a regular GET request, just write a few lines:
var req = require('tiny_request') req.get('http://google.com', function(body, response, err){ if (!err && response.statusCode == 200) { console.log(body) } }) 


Json


Since first of all the module will be used to work with the API, I decided that we need a simple mechanism for working with json.
To automatically deserialize the received response from the server, just pass the json parameter: true

 var req = require('tiny_request') req.get({ url: 'http://test.com/json', json: true}, function(body, response, err){ if (!err && response.statusCode == 200) { console.log(body) //body now is parsed JSON object } }) 


GET requests


For a request with GET parameters, it is enough to pass a query equal to an object with GET parameters, and to change the request port, it is enough to pass the port parameter:
 req.get({ url: 'http://test.com', query: { test: 'test' }, port: 8080}, function(body, response, err){ if (!err && response.statusCode == 200) { console.log(body) } }) 


POST Multipart


Where do without POST requests and file transfer?
 var data = { image: { value: fs.createReadStream('photo.png'), filename: 'photo.png', contentType: 'image/png' }, test: 'test' } req.post({ url: 'http://test.com', multipart: data }, function(body, response, err){ if (!err && response.statusCode == 200) { console.log(body) } }) 


POST forms


Working with forms is also very simple:

 var form = { test: 'test' } req.post({ url: 'http://test.com', form: form}, function(body, response, err){ if (!err && response.statusCode == 200) { console.log(body) } }) 


HTTP headers


To add headers, just pass the headers parameter:

 var headers = { 'Test-Header': 'test' } req.post({ url: 'http://test.com', headers: headers}, function(body, response, err){ if (!err && response.statusCode == 200) { console.log(body) } }) 


Pipe stream


Work with streams is also simple:

 req.get({url: url, pipe: stream}) 


All sources can be found on GitHub: github.com/Naltox/tiny_request

Source: https://habr.com/ru/post/264583/


All Articles