I wanted to use the node-imagemagick library but was getting weird error messages coming from the `identify` binary although I had installed ImageMagick through brew (brew install imagemagick).
I fixed it by grabbing the latest libfreetype from another brew package and linking it to the old library:
UPDATE: Amazon hosting may include Heroku or other services using Amazon as infrastructure. According to the certificate type column in the raw data, at least 6 domains are using Heroku.
Only a few weeks ago, there seemed to be absolutely no interest for tech startups in Shenzhen, China (or at least, among the English speaking community). As a startup guy, I was pretty upset by the seemingly nonexistent community. Of course, there was Hong Kong nearby with a vibrantcommunity but I wanted something in Shenzhen. I decided I’d prove myself wrong by creating a ”Startups and technology SZ” group on a popular expat social network called ShenzhenStuff.com.
It turned I was wrong about the lack of interest! The group grew to 32 members within only a few days. Within the same time frame, Michael Michelini, an American expat, and his associates were officially launching a coworking space aimed at web workers and freelancers. Talk about timing! Michael from SZTeam offered to host and run a first “Startup Tuesday” meeting which turned out to be a huge success.
Michael wrote a nice outline of the event and published his slides. The ~50 (I suck at guesstimates) attendees came from all kinds of backgrounds (technical, business, finance, curious people, etc.) and the crowd was about half foreigners, half Chinese.
For the upcoming events, many suggestions were made: invite speakers to talk about a specific topic, co-founder “speed dating”, startup weekends, pitch nights, etc. I’m particularly interested in co-founder speed dating as I’m looking for a co-founder :)
This first meeting was a huge success and Michael deserves all the credit. I would also recommend SZTeam to freelancers or anyone who is working on a startup. The people are friendly, there is a nice conference room, free coffee and the pricing is pretty cheap: hot desk for 500 RMB/month (80 USD/month) and fixed desk for 1500 RMB/month (235 USD/month).
As well all know, Javascript isn’t allowed in Posterous themes. Luckily, iframes are and that’s what we’ll use to go around the no Javascript limitation.
Simply go to your Posterous dashboard, click "Settings" on the top right, then click the "Edit Theme" button and select the "Advanced tab". Now, all you have to do is paste one of the following snippets where you want the button to show up and click the "Save, I’m done!" button.
Standard button:
Tall button:
That’s all you have to do to integrate Google +1 to your Posterous.
If you want to host the script yourself, the source code is available on Github:
UPDATE: There is now a Node.js addon for loading and calling dynamic libraries using pure JavaScript: node-ffi. Also, node-waf is no longer being used to compile Node.js extensions.
The full source code of this tutorial is available from github:
git clone git://github.com/olalonde/jsnotify.git
You can also install it through npm:
npm install notify
The code was tested on Ubuntu 10.10 64-bit and Node.js v0.5.0-pre.
Getting started
First let’s create a node-notify folder and with the following directory structure.
.
|-- build/ # This is where our extension is built.
|-- demo/
| `-- demo.js # This is a demo Node.js script to test our extension.
|-- src/
| `-- node_gtknotify.cpp # This is the where we do the mapping from C++ to Javascript.
`-- wscript # This is our build configuration used by node-waf
This fine looking tree was generated with the tree utility.
Now let’s create our test script demo.js and decide upfront what our extension’s API should look like:
12345678
// This loads our extension on the notify variable. // It will only load a constructor function, notify.notification().varnotify=require("../build/default/gtknotify.node");// path to our extensionvarnotification=newnotify.notification();notification.title="Notification title";notification.icon="emblem-default";// see /usr/share/icons/gnome/16x16notification.send("Notification message");
Writing our Node.js extension
The Init method
In order to create a Node.js extension, we need to write a C++ class that extends node::ObjectWrap. ObjectWrap implements some utility methods that lets us easily interface with Javascript.
#include <v8.h> // v8 is the Javascript engine used by Node#include <node.h>// We will need the following libraries for our GTK+ notification #include <string>#include <gtkmm.h>#include <libnotifymm.h>usingnamespacev8;classGtknotify:node::ObjectWrap{private:public:Gtknotify(){}~Gtknotify(){}staticvoidInit(Handle<Object>target){// This is what Node will call when we load the extension through require(), see boilerplate code below.}};/* * WARNING: Boilerplate code ahead. * * See https://www.cloudkick.com/blog/2010/aug/23/writing-nodejs-native-extensions/ & http://www.freebsd.org/cgi/man.cgi?query=dlsym * * Thats it for actual interfacing with v8, finally we need to let Node.js know how to dynamically load our code. * Because a Node.js extension can be loaded at runtime from a shared object, we need a symbol that the dlsym function can find, * so we do the following: */v8::Persistent<FunctionTemplate>Gtknotify::persistent_function_template;extern"C"{// Cause of name mangling in C++, we use extern C herestaticvoidinit(Handle<Object>target){Gtknotify::Init(target);}// @see http://github.com/ry/node/blob/v0.2.0/src/node.h#L101NODE_MODULE(gtknotify,init);}
Now, we’ll have to we have to write the following code in our Init() method:
Declare our constructor function and bind it to our target variable. var n = require("notification"); will bind notification() to n: n.notification().
1234567891011121314
// Wrap our C++ New() method so that it's accessible from Javascript// This will be called by the new operator in Javascript, for example: new notification();v8::Local<FunctionTemplate>local_function_template=v8::FunctionTemplate::New(New);// Make it persistent and assign it to persistent_function_template which is a static attribute of our class.Gtknotify::persistent_function_template=v8::Persistent<FunctionTemplate>::New(local_function_template);// Each JavaScript object keeps a reference to the C++ object for which it is a wrapper with an internal field.Gtknotify::persistent_function_template->InstanceTemplate()->SetInternalFieldCount(1);// 1 since a constructor function only references 1 object// Set a "class" name for objects created with our constructorGtknotify::persistent_function_template->SetClassName(v8::String::NewSymbol("Notification"));// Set the "notification" property of our target variable and assign it to our constructor functiontarget->Set(String::NewSymbol("notification"),Gtknotify::persistent_function_template->GetFunction());
Declare our attributes: n.title and n.icon.
12345
// Set property accessors// SetAccessor arguments: Javascript property name, C++ method that will act as the getter, C++ method that will act as the setterGtknotify::persistent_function_template->InstanceTemplate()->SetAccessor(String::New("title"),GetTitle,SetTitle);Gtknotify::persistent_function_template->InstanceTemplate()->SetAccessor(String::New("icon"),GetIcon,SetIcon);// For instance, n.title = "foo" will now call SetTitle("foo"), n.title will now call GetTitle()
Declare our prototype method: n.send()
123
// This is a Node macro to help bind C++ methods to Javascript methods (see https://github.com/joyent/node/blob/v0.2.0/src/node.h#L34)// Arguments: our constructor function, Javascript method name, C++ method nameNODE_SET_PROTOTYPE_METHOD(Gtknotify::persistent_function_template,"send",Send);
Our Init() method should now look like this:
12345678910111213141516171819202122
// Our constructorstaticv8::Persistent<FunctionTemplate>persistent_function_template;staticvoidInit(Handle<Object>target){v8::HandleScopescope;// used by v8 for garbage collection// Our constructorv8::Local<FunctionTemplate>local_function_template=v8::FunctionTemplate::New(New);Gtknotify::persistent_function_template=v8::Persistent<FunctionTemplate>::New(local_function_template);Gtknotify::persistent_function_template->InstanceTemplate()->SetInternalFieldCount(1);// 1 since this is a constructor functionGtknotify::persistent_function_template->SetClassName(v8::String::NewSymbol("Notification"));// Our getters and settersGtknotify::persistent_function_template->InstanceTemplate()->SetAccessor(String::New("title"),GetTitle,SetTitle);Gtknotify::persistent_function_template->InstanceTemplate()->SetAccessor(String::New("icon"),GetIcon,SetIcon);// Our methodsNODE_SET_PROTOTYPE_METHOD(Gtknotify::persistent_function_template,"send",Send);// Binding our constructor function to the target variabletarget->Set(String::NewSymbol("notification"),Gtknotify::persistent_function_template->GetFunction());}
All that is left to do is to write the C++ methods that we used in our Init method: New, GetTitle, SetTitle, GetIcon, SetIcon, Send
Our constructor method: New()
The New() method creates an instance of our class (a Gtknotify object), sets some default values to our properties and returns a Javascript handle to this object. This is the expected behavior when calling a constructor function with the new operator in Javascript.
12345678910111213141516
std::stringtitle;std::stringicon;// new notification()staticHandle<Value>New(constArguments&args){HandleScopescope;Gtknotify*gtknotify_instance=newGtknotify();// Set some default valuesgtknotify_instance->title="Node.js";gtknotify_instance->icon="terminal";// Wrap our C++ object as a Javascript objectgtknotify_instance->Wrap(args.This());returnargs.This();}
Our getters and setters: GetTitle(), SetTitle(), GetIcon(), SetIcon()
The following is pretty much boilerplate code. It boils down to back and forth conversion between C++ values to Javascript (V8) values.
123456789101112131415161718192021222324
// this.titlestaticv8::Handle<Value>GetTitle(v8::Local<v8::String>property,constv8::AccessorInfo&info){// Extract the C++ request object from the JavaScript wrapper.Gtknotify*gtknotify_instance=node::ObjectWrap::Unwrap<Gtknotify>(info.Holder());returnv8::String::New(gtknotify_instance->title.c_str());}// this.title=staticvoidSetTitle(Local<String>property,Local<Value>value,constAccessorInfo&info){Gtknotify*gtknotify_instance=node::ObjectWrap::Unwrap<Gtknotify>(info.Holder());v8::String::Utf8Valuev8str(value);gtknotify_instance->title=*v8str;}// this.iconstaticv8::Handle<Value>GetIcon(v8::Local<v8::String>property,constv8::AccessorInfo&info){// Extract the C++ request object from the JavaScript wrapper.Gtknotify*gtknotify_instance=node::ObjectWrap::Unwrap<Gtknotify>(info.Holder());returnv8::String::New(gtknotify_instance->icon.c_str());}// this.icon=staticvoidSetIcon(Local<String>property,Local<Value>value,constAccessorInfo&info){Gtknotify*gtknotify_instance=node::ObjectWrap::Unwrap<Gtknotify>(info.Holder());v8::String::Utf8Valuev8str(value);gtknotify_instance->icon=*v8str;}
Our prototype method: Send()
First we have to extract the C++ object this references. We then build our notification using the object’s properties (title, icon) and finally display it.
123456789101112131415161718
// this.send()staticv8::Handle<Value>Send(constArguments&args){v8::HandleScopescope;// Extract C++ object reference from "this"Gtknotify*gtknotify_instance=node::ObjectWrap::Unwrap<Gtknotify>(args.This());// Convert first argument to V8 Stringv8::String::Utf8Valuev8str(args[0]);// For more info on the Notify library: http://library.gnome.org/devel/libnotify/0.7/NotifyNotification.html Notify::init("Basic");// Arguments: title, content, iconNotify::Notificationn(gtknotify_instance->title.c_str(),*v8str,gtknotify_instance->icon.c_str());// *v8str points to the C string it wraps// Display the notificationn.show();// Return valuereturnv8::Boolean::New(true);}
Compiling our extension
node-waf is the build tool used to compile Node extensions which is basically a wrapper for waf. The build process can be configured with a file called wscript in our top directory:
1234567891011121314151617
defset_options(opt):opt.tool_options("compiler_cxx")defconfigure(conf):conf.check_tool("compiler_cxx")conf.check_tool("node_addon")# This will tell the compiler to link our extension with the gtkmm and libnotifymm libraries.conf.check_cfg(package='gtkmm-2.4',args='--cflags --libs',uselib_store='LIBGTKMM')conf.check_cfg(package='libnotifymm-1.0',args='--cflags --libs',uselib_store='LIBNOTIFYMM')defbuild(bld):obj=bld.new_task_gen("cxx","shlib","node_addon")obj.cxxflags=["-g","-D_FILE_OFFSET_BITS=64","-D_LARGEFILE_SOURCE","-Wall"]# This is the name of our extension.obj.target="gtknotify"obj.source="src/node_gtknotify.cpp"obj.uselib=['LIBGTKMM','LIBNOTIFYMM']
We’re now ready to build! In the top directory, run the following command:
node-waf configure && node-waf build
If everything goes right, we should now have our compiled extension in ./build/default/gtknotify.node. Let’s try it!
123456
$ node
> var notif= require('./build/default/gtknotify.node');
> n= new notif.notification();
{ icon: 'terminal', title: 'Node.js'}> n.send("Hello World!");
true
The previous code should display a notification in the top right corner of your screen!
Packaging for npm
That’s pretty cool, but how about sharing your hard work with the Node community? That’s primarily what the Node Package Manager is used for: making it easy to import extensions/modules and distribute them.
Packaging an extension for npm is very straightforward. All you have to do is create a package.json file in your top directory which contains some info about your extension:
{// Name of your extension (do not include node or js in the name, this is implicit). // This is the name that will be used to import the extension through require()."name":"notify",// Version should be http://semver.org/ compliant"version":"v0.1.0"// These scripts will be run when calling npm install and npm uninstall.,"scripts":{"preinstall":"node-waf configure && node-waf build","preuninstall":"rm -rf build/*"}// This is the relative path to our built extension.,"main":"build/default/gtknotify.node"// The following fields are optional:,"description":"Description of the extension....","homepage":"https://github.com/olalonde/node-notify","author":{"name":"Olivier Lalonde","email":"olalonde@gmail.com","url":"http://www.syskall.com/"},"repository":{"type":"git","url":"https://github.com/olalonde/node-notify.git"}}
For more details on the package.json format, documentation is available through npm help json. Note that most fields are optional.
You can now install your new npm package by running npm install in your top directory. If everything goes right, you should be able to load your extension with a simple var notify = require('your-package-name');. Another useful command is npm link which creates a symlink to your development directory so that any change to your code is reflected instantly - no need to install/uninstall perpetually.
Assuming you wrote a cool extension, you might want to publish it online in the central npm repository. In order to do that, you first need to create an account:
$ npm adduser
Next, go back to the root of your package code and run:
$ npm publish
That’s it, your package is now available for anyone to install through the npm install your-package-name command.
Conclusion
Writing a native Node extension can be cumbersome and verbose at times but it is well worth the hard earned bragging rights!
Thanks for reading. Let me know in the comments if you run into any problem, I’ll be glad to help.
If you liked this, maybe you’d also like what I tweet on Twitter! Might even want to hire me?
Here’s a quick way to expand a (VDI) Virtual Disk Image in VirtualBox 3.
Create a new VDI with the new size of your choice. (File / Virtual
Media Manager / New…)
Run this command:
$ VBoxManage clonehd --existing old.vdi new.vdi
This may take a few minutes.
Simply replace the attached old.vdi with the new.vdi in your virtual machine’s storage settings.
You will need to extend your partition from your guest OS. This can be done under Windows 7 from the control panel (Create and format hard disk partitions) and with GParted in Ubuntu and compatible Linux distributions.
/* * DISCLAIMER: THIS CODE IS FOR EDUCATIONAL PURPOSES ONLY. USE AT YOUR OWN RISKS. * * This code shows the basic workings of a shell. * * Append "/path/to/dashell" to /etc/shells, to make it a valid shell: * sudo echo "/path/to/dashell" >> /etc/shells * * Change your "username"'s shell. "username" should have execute permission for the shell: * chsh --shell /path/to/dashell username * */#include <unistd.h>#include <string.h>#include <stddef.h>#include <stdlib.h>#include <stdio.h>#include <ctype.h>#include <sys/signal.h>#define STDIN 0#define STDOUT 1#define STDERR 2#define BUFFER_SIZE 1024voidparse_arguments(charbuffer[],int*args_count,char*args[]){char*delimiters=" \r\n";char*token;*args_count=0;// "abc def ghi" => {"abc", "def", "ghi"}while(token=strsep(&buffer,delimiters)){args[*args_count]=token;(*args_count)++;}}intmain(intargc,constchar*argv[]){// The weird characters are used to format the text's appearance.// See http://en.wikipedia.org/wiki/ANSI_escape_codecharprompt[]="\033[1mdashell\033[2m>\033[0m ";charexec_error[]="Cannot execute program %s.\n";charbuffer[BUFFER_SIZE+1];intargs_count;char*args[BUFFER_SIZE];intn;while(1){write(STDOUT,prompt,strlen(prompt)+1);n=read(STDIN,buffer,BUFFER_SIZE);// Read from STDIN (keyboard input)buffer[n]='\0';// Null character to indicate string end// "abc def ghi" => {"abc", "def", "ghi"}parse_arguments(buffer,&args_count,args);// No argumentsif(args_count==0||strcmp(args[0],"")==0)continue;// Argument = exitif(strcmp(args[0],"exit")==0)exit(0);pid_tchild_pid=fork();// Duplicate processif(child_pid==0){// Childif(execvp(args[0],args)<0){// Replace executable code by command passedfprintf(stderr,exec_error,args[0]);}}else{// Parent// Wait for child to finishwait();}}}
Bind a Javascript function to your own C++ function
For the sake of demonstration and to impress your co-workers, we will bind a Javascript function “alert()“ that will display desktop notifications through the GTK library. Here’s what the end result looks like:
You can get the full source code of this tutorial from github:
git clone git://github.com/olalonde/jsnotify.git
This tutorial was tested on Ubuntu 10.04 and 10.10 64-bit but should work fine on any Linux distribution. The notification part requires the GTK+ library.
We can now move into the V8 directory and try to compile!
cd v8;
scons arch=x64;
The “arch=x64” option specifies that we want to build a 64-bit version of V8 (the default value would be 32-bit otherwise).
If V8 compiled fine, you should now have a libv8.a file in your v8/ directory. As you probably guessed, libv8.a is the library that our C++ program will use to execute Javascript code.
So, if everything compiled fine, just skip to the next section. Otherwise, keep on reading.
When you get errors as a result of compiling third party code, it is usually due to the fact that the compiler can’t find required libraries (/usr/lib) and/or their associated header files (/usr/lib/include). The latter are usually available through packages conventionally named libname-dev . In order to find out which package installs a given file, there is a neat utility called apt-file.
The apt-file search command lists the package(s) that install a given file (missing-header-file.h in this case). If there are more than one package listed, we have to take a semi-educated guess on which package we should install based on its name (let me know in the comments if you know of a better trick!). We then simply install the package with the usual apt-get install package-name command.
Hint: If you are on Ubuntu 10.04, you might need to install the following packages:
sudo apt-get install libc6-dev-i368 lib32stdc++6
Now that we’ve installed all the missing files, the compilation should work. Let’s move on to the next section.
If you are still stuck with compiling V8, this tutorial might help.
Building our own Javascript API
Now that we have successfully compiled the V8 library, we will build our own C++ project that will be “Javascript scriptable”. This means that our program will be able to run Javascript code which in turn will be able to call our custom C++ functions.
Note: You can also get the full source code of this tutorial from my jsnotify github repository): git clone git://github.com/olalonde/jsnotify.git
First let’s create our file structure.
jsnotify/
|-- deps/ # third party code
| `-- v8 # move your v8 folder here
`-- src/ # our code goes here
`-- jsnotify.cpp
Now let’s copy the sample code available at deps/v8/samples/shell.cc and paste it into jsnotify.cpp. The sample code given by V8 let’s you execute a Javascript file or start an interactive Javascript shell. It also binds some useful Javascript functions such as print() which will output text to the terminal.
Let’s try to compile this!
g++ src/jsnotify.cpp;
Of course, this gives us a bunch of errors since we haven’t specified where the V8 header and library files are. Let’s try again!
This finally compiles! Now that we have our mini Javascript shell, let’s play a bit with it.
12345
$ ./a.out
V8 version 3.1.5
> var foo= “Hello World”;
> print(foo);
Hello World
Now, all we have to do is to create our custom alert() function in C++.
123456789101112131415161718192021
// INSERT THIS BEFORE int RunMain(int argc, char* argv[]) {// We need those two libraries for the GTK+ notification #include <gtkmm.h>#include <libnotifymm.h>v8::Handle<v8::Value>Alert(constv8::Arguments&args);// INSERT THIS AT END OF FILE // The callback that is invoked by v8 whenever the JavaScript 'alert'// function is called. Displays a GTK+ notification.v8::Handle<v8::Value>Alert(constv8::Arguments&args){v8::String::Utf8Valuestr(args[0]);// Convert first argument to V8 Stringconstchar*cstr=ToCString(str);// Convert V8 String to C stringNotify::init("Basic");// Arguments: title, content, iconNotify::Notificationn("Alert",cstr,"terminal");// Display notificationn.show();returnv8::Undefined();}
Now that we have our Alert C++ function, we need to tell V8 to bind it to the Javascript alert() function. This is done by adding the following code in the RunMain function:
123
// INSERT AFTER v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();// Bind the global 'alert' function to the C++ Alert callback.global->Set(v8::String::New("alert"),v8::FunctionTemplate::New(Alert));
Now, in order to compile, the compiler needs to know where to find the two header files we introduced. This is done using the pkg-config utility:
$./a.out
V8 version 3.1.5
> alert(“wow, it works!”);
You should see a nice notification in the top right of your screen! Note that you can also put you Javascript code in a file and pass the file name as an argument ./a.out filename.js.
Conclusion
It’s quite easy to make a C++ program “Javascriptable” with V8 and the proper setup. If you’d like to practice your newfound skills, I suggest you try to add a title argument to the alert function. You might also want to follow me on Posterous if you’d like to be informed when I post the follow up to this tutorial which will explain how to extend Node.js with our alert function.
That’s all for today, thanks for reading! Let me know in the comments if you run into any problem, I’ll be glad to help.
If you liked this, maybe you’d also like what I tweet on Twitter!
I recently stumbled upon a quite interesting piece of history buried in TechCrunch’s archives. It’s a July 2006 article written by Michael Arrington which introduces a “sort of “group send” SMS application” as he described it at the time. For those who haven’t guessed yet, the “application” he is referring to is now known as Twitter, a 190 million users strong social network and company currently valued at around $10 billion. Yet, at the time, very few people believed the startup had any chance of success and even fewer could have predicted it would grow to become a billion dollar company.
Here are some gems from the article and comments. It would be superfluous to comment them as I believe they speak for themselves. If you find yourself laughing at this (as I did), take a moment to realize just how wonderful the benefit of hindsight is.
All comments date from 2006. I didn’t include the names of the commenters (but they aren’t really hard to find).
There is also a privacy issue with Twttr. Every user has a public page that shows all of their messages. Messages from that person’s extended network are also public. I imagine most users are not going to want to have all of their Twttr messages published on a public website.
I do not understand the utility of adding the SMS messages to a public webpage or making messages from my network public. I would have to pass on that type of offering. The ability to make messages private should be added asap.
Odeo was a failure from the get go. No revenue model. I asked their VC - CRV - what the revenue model was a year ago and he said “to sell to someone bigger.” Okay, that was a web 1.0 answer, and now we get Twttr - an even dumber idea with no revenue model, but a 2.0 concept.
I think this is the dumbest thing ever! Who would want all their personal text messages on a public website for anyone to read and track?
Not innovative and not focused. Twttr sounds like a disaster in the making…
i do not want to be woken up at 4 a.m. because my friend got drunk and decided to text Twttr with “asdl im at barasdf sooo drunksalkfjs”…i find it interesting such an annoying feature is supposedly causing viral growth…i’m done developing social software if the key to success is to be intrusive
Finally, a last blog comment that caught my attention on an other old Twitter article:
It’s kinda wierd, John Resig and I had been thinking about building this exact system, though it never really got past the, “Wouldn’t it be cool if” stage. Meh, I’m just glad it exists now. It was a personal itch I wanted to scratch and I’m not going to complain at all if someone else scratches it. Plus the Odeo guys made it much prettier than I would have. - Bob Aman
I’d be curious to know if the John Resign being referred to is the same guy who went on to build jQuery. Did John Resig really almost build a Twitter before Twitter?
Here’s a line tracking robot I built with friends at university. I thought I would post it here before it sinks into oblivion. It was built using a 16bit micro-controller (ATmega16), a PCB, a small motor and some sensors. The programming was done in C/C++. Source code and hardware (if you can pick it up - Montreal) available upon request.
Any ideas of how I could turn it into something useful? I also got a proximity sensor if that can be of any use.