Add members to email list on Mailchimp API v3.0 using Node.js

Mailchimp v3.0 is really simple to use. Using Node.js http module we can very easily add members to email list in the following way:
var http = require('http');
var addToMailchimp = function (email){
  var subscriber = JSON.stringify({ "email_address": email, "status": "subscribed" });
  var options = {
    host: '<us111>.api.mailchimp.com',
    path: '/3.0/lists/<list-id>/members',
    method: 'POST',
    headers: { 'Authorization': 'randomUser <your-api-key>', 'Content-Type': 'application/json', 'Content-Length': subscriber.length }
  };

  var req = http.request(options, function (res) {
    console.log('status code: ' + res.statusCode);
    console.log('headers: ' + JSON.stringify(res.headers));
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
      console.log('\n\n===========chunk===============');
      console.log(chunk);
    });
    res.on('end', function(res) {
      console.log('\n\n=========end===============');
    });
    res.on('error', function (e) {
      console.log('ERROR: ' + e.message);
    });
  });

  req.write(subscriber);
  req.end();
};

Comments