Needle is a streamable HTTP client for making quick HTTP requests in Node.js application to consume RESTful web services, uploading and downloading streams of data etc.

It supports the following features out-of-the-box:

  • Both HTTP and HTTPS requests
  • All Node's native TLS options
  • Basic & Digest authentication with auto-detection
  • Multipart form-data for uploading files
  • HTTP Proxy forwarding, optionally with authentication
  • Streaming gzip or deflate decompression
  • Automatic XML & JSON parsing
  • 301/302/303 redirect following
  • Streaming non-UTF-8 charset decoding, via iconv-lite

In this tutorial, we'll discuss how to use Needle to send HTTP requests in Node.js application. For all our examples, we will use dummy Reqres REST API to simulate real application scenarios.

Installation

Depending on your package manager, you can install Needle by using either npm:

$ npm install needle --save

or yarn:

$ yarn add needle

Needle API

Needle supports both Promises and traditional callbacks for making HTTP requests. You can also streams the data by skipping the callback.

const needle = require('needle');
const fs = require('fs');

// using promises
needle('get', 'https://reqres.in/api/users')
    .then(res => {
        console.log(res.body);
    })
    .catch(err => {
        console.error(err);
    });

// using traditional callback
needle.get('https://reqres.in/api/users', (err, res, body) => {
    if (err) {
        console.error(err);
    };

    console.log(res.body); // or just `body` as it is an alias of `res.body`
});

// skip callback, using streams
let out = fs.createWriteStream('got.jpg');
needle.get('https://i.imgur.com/7zTMFOe.jpg')
    .pipe(out)
    .on('finish', () => {
        console.log('pipe done');
    });

As you can see above, calling needle() directly returns a Promise. Just like Axios, Needle also provides aliases for all supported HTTP request methods: needle.get(), needle.post(), needle.put(), and so on. These aliases return a readable stream. Depending on the response's Content-Type, Needle automatically parses the response body to JSON or XML streams.

GET Request

The following code snippet shows how to use of needle.get() method to get a list of users:

const needle = require('needle');

needle.get('https://reqres.in/api/users', (err, res, body) => {
    if (err) {
        console.error(err);
    };
    console.log(body);
});

If you want to pass the query parameters, you can either append them to URL like following:

needle.get('https://www.google.com/search?q=needle', (err, res, body) => {
   if (err) {
       console.error(err);
   };
   console.log(body);
});

or use needle.request() method to pass parameters as an object:

needle.request('get', 'https://www.google.com/search', { q: 'needle' }, (err, res) => {
   if (err) {
       console.error(err);
   };
   console.log(res.body);
});

POST Request

You can send an HTTP post request using needle.post() method:

const needle = require('needle');

needle.post('https://reqres.in/api/users',
   {
       name: 'Atta',
       job: 'Freelance Developer'
   }, (err, res) => {
       if (err) {
           console.error(err);
       };
       console.log(res.body);
   });

By default, the request body is sent as a query string. But you can pass json: true in options to set the content type to application/json and send request body as JSON string, instead of a query string.

const needle = require('needle');

needle.post('https://reqres.in/api/users',
    {
        name: 'Atta',
        job: 'Freelance Developer'
    }, { json: true }, (err, res) => {
        if (err) {
            console.error(err);
        };
        console.log(res.body);
    });

PUT Request

Using needle.put() method, you can send an HTTP put request:

const needle = require('needle');

needle.put('https://reqres.in/api/users/2',
    {
        name: 'Atta',
        job: 'MEAN Stack Developer'
    }, { json: true }, (err, res) => {
        if (err) {
            console.error(err);
        };
        console.log(res.body);
    });

DELETE Request

Needle provides needle.delete() method to perform an HTTP delete request:

const needle = require('needle');

needle.delete('https://reqres.in/api/users/2', null, (err, res) => {
        if (err) {
            console.error(err);
        };
        console.log(res.statusCode);
    });

Interested in learning more about HTTP clients in Node.js? Check out 7 Ways to Make HTTP Requests in Node.js tutorial.

Conclusion

Needle is a streamable HTTP client for Node.js which supports proxy, iconv, redirect following, cookie, deflate and multi-part requests. With Needle, you can use both promises and callbacks to perform HTTP requests.

For more configuration options, check out Needle docs on GitHub. If you have any question or feedback, please feel free to send me a tweet anytime.

Happy Coding 😍

Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV.

πŸ™Œ Join the weekly newsletter and get the latest tutorials from my blog and around the internet.
No spam, ever. You can unsubscribe anytime.

Need help to start a new Spring Boot or MEAN stack project? I am available for contract work. Hire me to accomplish your business goals with engineering and design. Let’s talk about your project: hi@attacomsian.com.