Posting a new ATOM entry to Atom Hopper using Node.js

Post to Twitter

Previously I blogged about how you can use Apache Abdera to post ATOM entries to an AtomPub server like Atom Hopper. Today I’ll show you how to do something similar but with Node.js.


[ad name=”Google Adsense”]

Note: The code below is a simplistic example and would need modifications to become production quality. This code can be used for testing purposes, etc.

The Node.js documentation has some sample code to perform an HTTP POST which is exactly what we need to do to post to Atom Hopper. The sample code to POST to Atom Hopper (or any AtomPub server) looks like the following:

var http = require('http');

var data = '<entry xmlns="http://www.w3.org/2005/Atom"><title type="text">Good Evening</title>'
	+ '<author><name>Chad</name></author><content type="text">This is the content</content></entry>';

var headers = {
    'Content-Type': 'application/atom+xml',
    'Content-Length': Buffer.byteLength(data, 'utf8')
};

var opts = {
    host: 'localhost',
    port: 8080,
    method: 'POST',
    path: '/atomhopper-1.0.2-SNAPSHOT/namespace/feed/',
    headers: headers
};

var req = http.request(opts, function (response) {
	var returnedData = '';
    response.on('data', function (chunk) {
        returnedData += chunk;
    });
    response.on('end', function () {
        console.log('Returned Data: ' + returnedData);
    });
});

req.on('error', function (e) {
    console.log("Got Error: " + e.message);
});

if(opts.method === 'POST') {
    req.write(data);
}

req.end()

The result will be similar to this:

Returned Data:
<entry xmlns="http://www.w3.org/2005/Atom">
  <title type="text">Good Evening</title>
  <author>
    <name>Chad</name>
  </author>
  <content type="text">This is the content</content>
  <id>urn:uuid:e36ef071-65aa-49fb-87c0-6c0219211f0f</id>
  <link href="http://localhost:8080/atomhopper-1.0.2-SNAPSHOT/namespace/feed/entries/urn:uuid:e36ef071-65aa-49fb-87c0-6c0219211f0f" rel="self" />
  <updated>2012-05-01T22:38:50.886Z</updated>
</entry>

Post to Twitter

This entry was posted in Atom Hopper, JavaScript, Node.js, Open Source. Bookmark the permalink.