CommonJS Modules, node’s require() and private members
CommonJS Modules, node's require() and private members
Interestingly, node.js module documentation doesn't even mention CommonJS or the specification proposal it implements. I won't go over CommonJS Modules 1.0 in-depth in this post, but I suggest you read both of these links if you plan to explore node.js development.
An important take-away from this blog post (so important that I state it first) is that node.js caches modules. A module's exports are nothing more than an object. When you set a function or property to be exported, you're setting it on an object.
Conceptually, this:
var someFunction = function(){ /* implement */ };
module.exports.someFunction = exports.someFunction = someFunction;
...is the same as doing this outside of CommonJS modules...
var someFunction = function(){ /* implement */ };
var exports = {};
exports.someFunction = someFuntion;
I know, that seems like it should be common sense. When node.js caches the exports object at the application level, I think understanding this can become hairy -- especially if you come from a compiled language background.
For example, consider the following module.
var count = 0;
var doSomethingShared = function(){
count += 1;
console.log("Shared call count: %d", count);
};
var doSomethingNotShared = function(){
console.log("Other modules don't know about me!");
};
module.exports.shared = exports.shared = doSomethingShared;
module.exports.unshared = exports.unshared = doSomethingNotShared;
We can require this module easily and play around with it in node REPL:
$ node
> var example = require('./example.js');
undefined
> example.shared()
Shared call count: 1
undefined
> example.shared()
Shared call count: 2
undefined
> example.shared()
Shared call count: 3
undefined
> example.shared()
Shared call count: 4
undefined
> example.unshared()
Other modules don't know about me!
undefined
In the same REPL instance, you can re-require the module and see that 'count' is indeed shared:
> var example2 = require('./example.js');
undefined
> example2.shared()
Shared call count: 5
undefined
> example2.shared()
Shared call count: 6
undefined
You can even require the shared function directly:
> var shared = require('./example.js').shared;
undefined
> shared()
Shared call count: 7
undefined
> shared()
Shared call count: 8
undefined
I think you get the point; private variables which aren't exported are shared. In this example, 'count' is a private static property of the module.
Why this matters
This is very important, because when working in the asynchronous environment of node.js you have to be aware about *what* is being cached privately at the module level. In addition to this, if you plan to cache functions for whatever reason, you have to be incredibly sure you know what you're doing. I recommend to NEVER CACHE CALLBACK FUNCTIONS.
As an example of this statement, I've created a sample file processor script in the github repo as fs-example.js. That script reads this blog's directory in the repo, then loops over the files and executes 'processor', which is a custom broken module displaying the above problem. fs-example.js does an inline require, which as you've seen above doesn't make a difference.
The problem I'll display here exists because async calls are likely to take different lengths of time to execute. My example is using the linux commands 'head -1' and 'tail -1' on each file to get the first and last lines, respectively. These commands are nearly instantaneous, so I'm using a random setTimeout to display the problem with caching functions. You could easily modify these scripts to 'head' and 'tail' different web sites. But, whatever. Because head.js and tail.js are simple spawn wrappers, I'll focus on processor.js, which is where the potential bugginess exists.
// begin processor.js
var head = require('./head'),
tail = require('./tail');
// don't do this IRL
var callback = null;
var processor = function(file, cb){
if('function' === typeof cb){
callback = cb;
}
// these fail
head(file, function(d){
callback(d)
});
tail(file, function(d){
callback(d)
});
// these succeed
// head(file, callback);
// tail(file, callback);
};
module.exports = exports = processor;
This is a simple file for having such a subtle bug. The file includes the customized head and tail scripts. Then, it creates a function that tags a file, caches the callback function, and calls head and tail to execute the callback. You'll notice the commented-out lines at the end that claim 'these succeed'. Here's why...
When a callback is passed directly to a function as is done with head(file, callback), the function itself is passed as a reference. Meaning, when the head module executes that callback, it will always execute the referenced callback. Now, what if another developer wants to add logging or other processing of the data? You'll likely get something like the example, where a function is created and callback is called directly (rather than the cb passed into the function originally). Because 'callback' is cached at the module level and shared across calls to processor, the scope created by the processor function is shared with the anonymous function callback and points to whatever is the most recent callback function rather than what one might expect to be the intended function.
We could avoid the problem in the above non-commented code by referencing the 'cb' parameter rather than the cached 'callback' variable. This is because processor creates a closure over 'callback', but 'cb' would always be within the current execution context.
You can play around with the code from this post, which is available on github.
Generating sprites with HTML5 canvas (node-canvas)
About a week ago, I posted about drawing simple shapes in HTML5. HTML5's Canvas isn't only useful on the client side.
About a year ago, I rewrote my Quaketracker mashup which pulls rss content from USGS and displays markers on a Google Map. For part of this rewrite, I wanted to use custom markers to indicate the magnitude of the earthquake, both numerically and colorfully. That task was more involved than I realized it would be. There doesn't seem to be any easy way to generate such a sprite in The Gimp or other graphics software, so I set out to generate a sprite of magnitudes 0.0 through 9.9 with a color range from yellow to orange using node-canvas. This actually made the task very simple.
Before writing the script, I had to decide on an image. I created a pretty simple quote-bubble-like marker with a white background and a black outline. The image is 35x35 square with some transparency padding the actual marker image. This allows me to calculate the layout pretty easily. The white background on black outline gives me a very specific color to replace with the desired color of intensity.
node-canvas is a custom implementation of Canvas for node.js. When I originally wrote this script, I had a few issues compiling node-canvas. When I tweaked the script today, I had no issues. However, it seems like some things are not well-documented or incomplete (PixelArray).
Scripting it in node.js
A lot of times, if your script writes out to files, it's best to check for dependencies and cause your script to exit if they're not met. For example, I know this script is completely useless without node-canvas, so I can probe for the availability of that module and provide directions for installation. I'd do this before attempting to load any other functions from the canvas module. You could also check for versions at this point. If someone runs this script with node-canvas 0.6.0 it will still work, but this may not be the case with other modules. Here's how I start off the script.
var p = require('util').puts;
try {
var probe = require('canvas');
} catch(e) {
p("Cannot find node-canvas module.");
p("Did you install dependencies:\n");
p("\tnpm install -d");
process.exit();
}
var fs = require('fs');
var Canvas = require('canvas');
var Image = Canvas.Image;
var canvas, ctx, baseImage, outImage, img;
I don't usually use 'global' variables like those in the last line of the above snippet for applications or client-side scripting. For a script like this, you could have everything as a global variable as long as the names don't clash with your imported modules.
To initialize shared variables, I like to define an init() function and call that function at the end of the script. This is pretty common in other languages like Ruby and Python, so why node server-side JavaScript?
var init = function() {
// our working image is 35x35, we want 10x10 sheet of sprites
canvas = new Canvas(35*10,35*10);
ctx = canvas.getContext('2d');
baseImage = __dirname + '/base.png';
outImage = __dirname + '/markers.png';
// pre-load the image
img = new Image;
img.onload = function() {
processImage(fileProcessingComplete);
};
img.src = baseImage;
};
The cool thing about node-canvas is that the usage is very similar to the Canvas API implemented in browsers supporting the HTML5 Canvas. In fact, aside from the __dirname special property of node.js, you should be able to drop this init function into a browser with no problems. For this script, I want 100 different magnitudes to be generated from 0.0 through 9.9 (00-99 is 100) so the canvas is initialized to 10 rows and 10 columns of 35x35 squares. Just like a client-side Image object, we want to bind any post-processing of the image via the onload() function.
I'm going to Memento you a bit, and for that I'm sorry but the end is the easier concept. When all the processing is complete, we want to pull image data from the Canvas element and write it out to a file.
var fileProcessingComplete = function() {
var out = fs.createWriteStream(outImage),
stream = canvas.createPNGStream();
stream.on('data', function(chunk){
out.write(chunk);
});
// when PNG stream is done, drain WriteStream
stream.on('end', function(){
p('saved ' + outImage);
out.destroySoon();
});
};
Accessing streams in node.js is usually done asynchronously. We can take chunks of data from the ReadStream of createPNGStream() and pump that to the WriteStream of the output file. When the data from the PNG is done streaming, we tell the output stream to finish writing its buffered data and destroy itself. It sounds intense, but it's pretty straightforward.
Processing the colors and marker images is the fun part. To match the function call in the init function, we just create a function with a callback in the standard way.
var processImage = function(cb) {
// other code removed
if(typeof cb === "function") {
cb.call(this);
}
}
If there's a callback function passed as a parameter, when processImage is finished, it will call that function passing the current scope as the execution scope and no parameters.
To draw out the custom marker, we'll want to define how we want to display the text and at what color we want to have the 0.0 marker start.
ctx.font = 'normal 12px Impact'; ctx.textAlign = 'center'; var color = [255, 255, 0, 235];
The color array represents red, green, blue, and alpha channel (opacity). This may look odd if you're used to specifying alpha channels in css as "rgba(255,255,0,0.92)", but that value of 235 will give roughly 92% opacity.
We can make the script run pretty quickly by using a second canvas 2d context for the recolor phases (which modifies every white pixel).
// use a temp Canvas and Context of 35x35 size.
var tempCanvas = new Canvas(35,35);
var tempCtx = tempCanvas.getContext('2d');
This is an optimization I made today when tweaking the original script. In the original version of this script, I would write the base image to the output canvas then iterate over 'NxN' pixels on the output canvas to change the color of one pixel. Using a temporary canvas context, we only have to iterate over 35 pixels wide by 35 pixels high for every new marker. This not only speeds up the process, but it could be a difference of having a script that won't run on slower machines.
For each of the desired 100 magnitudes, we'll want to find the x and y values (top-left pixel) to which we'll write the updated marker. For every 1/2 magnitude, the Green color value decrements by 13 points.
for(var magnitude = 0; magnitude <= 100; magnitude++) {
var y = 35 * Math.floor(magnitude/10),
x = ( 35*(magnitude % 10) );
// This increments the color slightly
if(magnitude % 5 == 0){
color[1] = color[1] - 13;
}
// some code removed
ctx.fillText("" + parseFloat(magnitude / 10, 1), x + (35/2), y + (35/2), 35);
}
The last line of the above snippet fills the magnitude text on the output canvas. This could be moved to the next part of the script for a further optimization: instead of just modifying each white pixel's color, we could recolor and apply the text.
The part of the script which changes the color according to the magnitude looks like this:
tempCtx.drawImage(img, 0, 0, 35,35);
var imgData = tempCtx.getImageData(0, 0, 35, 35);
var data = imgData && imgData.data;
if(data) {
try {
for(var pixel=0;pixel<data.length;pixel=pixel+4) {
var red = data[pixel]
var green = data[pixel+1];
var blue = data[pixel+2];
var alpha = data[pixel+3];
if(red == 255 && green == 255 && blue == 255) {
data[pixel] = color[0];
data[pixel+1] = color[1];
data[pixel+2] = color[2];
data[pixel+3] = color[3];
}
}
} catch (err) { console.error(err.message); }
// Write our temp image data to the final canvas context
/* imageData, dx, dy, sx, sy, sw, sh */
ctx.putImageData(imgData,x,y,0,0, 35, 35);
}
Writing to the temporary canvas's 2d context gives us access to a data buffer which represents a 35x35 image where each pixel is represented by 4 bytes (rgba). Iterating this buffer by 4's, we can check that the given pixel (excluding alpha because that doesn't matter in this case) is white or rgba(255,255,255). If the pixel is white, we replace those 4 indexes with the values in our color array. When we're done iterating the buffer representing the 35x35 image, we can call putImageData on the output canvas. With that, the sprite is complete and our callback handles writing the file.
A note about putImageData
putImageData can be a strange beast. Notice the comment imageData, dx, dy, sx, sy, sw, sh... these are the parameters accepted by the function. Even the HTML5 Specs might make you go, "Uhm... what?" The idea is pretty simple once you understand it. You want to write a buffer (imgData) where the top-left pixel is at dx,dy. sx and sy (or dirtyX and dirtyY) represent a dirty rectangle of size sw x sh (or dirtyWidth by dirtyHeight).
If the imageData passed to the function is the same height and width as the target canvas context, you wouldn't want to overwrite every single pixel would you? You'd only want to overwrite pixels that have changed. Suppose in this script, I had an imageData object of 350x350 to complement the output canvas. When putting the modified imageData, I would have to calculate the current 35x35 box offset and write out the imageData to 0,0. As an example, if I wanted to overwrite the 35x35 box for the 9.9 magnitude marker with an imageData buffer of 350x350, I might write:
ctx.putImageData(imgData, 0, 0, 315, 315, 35, 35);
This would tell the context that although my buffer is 350x350, I've only changed a 35x35 rectangle starting at 315x15. Canvas is smart enough to only update those pixels rather than every pixel in the canvas.
On the other hand, in the script I've written, I only have an imageData object which represents a 35x35 buffer. So, I can tell putImageData to start at the point defined by (x,y) and write the buffer into a 35x35 rectangle. I like this method a little more, but it may not always be the case that you're writing a smaller buffer to the context.
The code
As always, the code for this blog post is available on github at jimschubert/blogs.
The sprite
Here's what the generated sprite looks like.
Proxy Objects
I started to familiarize myself with proxy objects a couple of years ago when I started used Fluent NHibernate on a pretty large project. NHibernate itself proxies objects to allow the framework to do its magic. Proxies are a fantastic thing. I spoke with a friend of mine today about some advanced coding techniques including proxy objects and IoC, which made me want to write a little about some of those topics.
From Wikipedia:
A proxy, in its most general form, is a class functioning as an interface to something else. The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate.
Charles Bretana gave an excellent and succinct definition of proxy objects on Stack Overflow back in 2008:
One purpose is to "pretend" to be the real class so a client component (or object) can "believe" it's talking to the "real" object, but inside the proxy, other stuff, (like logging, transactional support, etc.) is being done at the same time... Secondly, a proxy can be very cheap in comparson to the real object,. and often is used so that the real objects can be conserved (turned off or released to a pool to be used by other clients) when the client is not using them... The proxy stays "alive" and the client thinks it still has a connection to the real object, but whenever it "calls" the object, it is actually calling the proxy, which goes and gets another real object just to handle the call, and then releases the real object when the call is done.
I've created an example (available on github) which demonstrates how to proxy method calls in a few different ways, ranging from very simple to using Castle.DynamicProxy and interceptors. The code is written in C# and although the code doesn't handle some of the more advanced topics of proxy objects, such as resource pooling as Charles described, it will (I hope) introduce proxy objects in a comprehensible way.
Read on for killer examples.
Debug.WriteLine
I answered a question on StackOverflow last week which made me remember a few years ago when I also wondered, "Where does Debug.WriteLine go?!"
The answer is very simple (and no, I'm not peeved that I was the first to answer and didn't get accepted).
If you look at the Debug.WriteLine documentation on MSDN, you will see a ConditionalAttribute:
[ConditionalAttribute("DEBUG")]
public static void WriteLine(
string message
)
This attribute is one of a few* compiler-time attributes. In other words, the compiler looks for this attribute specifically and, if found and the DEBUG condition is met (i.e. 'DEBUG' is defined), THIS METHOD IS NOT COMPILED. That's pretty awesome, but you don't need to take my word for it. I've created a quick example.
Program.cs
Program.cs is a small program with three important pieces: Console.WriteLine, Debug.WriteLine, and a final Console.WriteLine. We have a before and after Console.WriteLine to show that Debug.WriteLine is not compiled into Program.exe when DEBUG is not defined.
using System;
using System.Diagnostics;
class Program {
static void Main(string[] args) {
Console.WriteLine("Console.WriteLine #1");
Debug.WriteLine("Debug.WriteLine");
Console.WriteLine("Console.WriteLine #2");
}
}
To compile normally, run
csc Program.cs
.
To compile with the DEBUG constant defined, run:
csc /define:DEBUG Program.cs
You can run Program.exe after both compiles, but you will see the same output.
The IL
You can use a tool called ildasm to dump the IL code of Program.exe (ildasm is part of the Windows SDK, after installation it can be found at, e.g., C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools).
Just open ildasm, choose File->Open and select Program.exe. Next, choose File->Dump. Choose 'Dump IL Code' and any other options you want.
Here is the output of the main method for both versions of the exe:
Program-NoDefines.il
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 24 (0x18)
.maxstack 8
IL_0000: nop
IL_0001: ldstr "Console.WriteLine #1"
IL_0006: call void [mscorlib]System.Console::WriteLine(string)
IL_000b: nop
IL_000c: ldstr "Console.WriteLine #2"
IL_0011: call void [mscorlib]System.Console::WriteLine(string)
IL_0016: nop
IL_0017: ret
} // end of method Program::Main
Program-DEBUGDefined.il
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 35 (0x23)
.maxstack 8
IL_0000: nop
IL_0001: ldstr "Console.WriteLine #1"
IL_0006: call void [mscorlib]System.Console::WriteLine(string)
IL_000b: nop
IL_000c: ldstr "Debug.WriteLine"
IL_0011: call void [System]System.Diagnostics.Debug::WriteLine(string)
IL_0016: nop
IL_0017: ldstr "Console.WriteLine #2"
IL_001c: call void [mscorlib]System.Console::WriteLine(string)
IL_0021: nop
IL_0022: ret
} // end of method Program::Main
As you can see, Debug.WriteLine is only added to Program.exe when we pass the DEFINE constant! Pretty cool, huh?
* The only other compiler-time attribute I know off-hand is ObsoleteAttribute, which will generate compiler warnings or errors if passing true as a second parameter into the constructor.
ASP.NET, AppDomains, and shadow-copying
I answered a question on StackOverflow nearly two years ago, and I'm surprised at how few votes it has received, despite comments such as:
+1 for teaching me something new today thanks. -kobe
Being one of my favorite answers, I thought I should discuss it on my blog a little more in-depth than just posting the SO answer. I'd like to briefly discuss what ASP.NET really is (in the context of IIS), why AppDomains are needed, and lastly what shadow-copying does for an application. There is no code associated with this post, and it is driven more by contemplation than by a specific resolution to a problem. So, I apologize in advance if it seems disjointed at times.
Allowing only a single instance of a .NET application
In the past, whenever I constrained an application to having only a single instance running at any given time, I naively walked a list of running processes to find a process with the same name as the currently-running process. If it exists, there's another instance, if not I would assume there is no other instance. This was a quick and dirty approach, because I didn't know of any other way. Of course, this would fail if the user renamed the process; total fail.
In CLR via C# by Jeffrey Richter, a much quicker solution is presented (leaving my naive solution to be only dirty). This solution uses a Semaphore to count references to a resource (the application) as it will be managed by the operating system.
Here is a simple console application to display how this would work:
class Program
{
const string Id = "af49d266-e4f4-4a63-b73c-f62c1144b584";
static void Main(string[] args)
{
bool thisInstance;
using (var semaphore = new Semaphore(0, 1, Id, out thisInstance))
{
if (thisInstance)
{
Console.WriteLine("This is the first instance!");
Console.ReadLine();
}
else
{
Console.WriteLine("There is another instance running.");
Console.ReadLine();
}
}
}
}
A semaphore is designed to limit access to a given resource. If you read the Wikipedia - Semaphore article, you'll see that a semaphore is described as a librarian handing out passes to study rooms. The librarian doesn't care who is in which room, only whether there are rooms available. There could be 10 rooms, there could be 100. In this single application example, we have 1 available resource which is the application identified by a constant Guid - "af49d266-e4f4-4a63-b73c-f62c1144b584". Because the operating system will use this string to uniquely identify our application, I've chosen a Guid over something simple like "MySemaphore" because the chances of a Guid being duplicated are theoretically nil.
Using this Semaphore constructor:
public Semaphore( int initialCount, int maximumCount, string name, out bool createdNew )
we can create a binary semaphore.
A binary semaphore allows us to have an on/off switch for running our application -- is the resource available or not? When we have 1 resource available, and the first application starts up, it decrements the count of available resources to 0. If this decrement occurs, the createdNew out parameter will be true. On the other hand, if an application starts up and the semaphore's available resource count is 0, createdNew will be false.
Notice in the code above that Console.ReadLine() is used in each block of the if statement to block execution. Why is this not located at the end of the Main method?
It's because Semaphore is a type derived from WaitHandle. WaitHandle implements the IDisposable interface, which is why the Semaphore is wrapped in a using block. When the code exits this using block, semaphore.Dispose() executes semaphore.Close() and the currently-held resource is released. This increments the available resources back to the maximum value of 1. In a real application, the first block would call the Application's Run() method and the else block would either display a message, terminate silently, or switch to the first process.
It is also possible to have any subsequent processes wait for the semaphore to release its lock on the resource. This would be accomplished by calling semaphore.WaitOne() in the else block:
class Program
{
const string Id = "af49d266-e4f4-4a63-b73c-f62c1144b584";
static void Main(string[] args)
{
bool thisInstance;
using (var semaphore = new Semaphore(0, 1, Id, out thisInstance))
{
if (thisInstance)
{
Console.WriteLine("This is the first instance!");
Console.ReadLine();
// Release resource
semaphore.Release();
}
else
{
Console.WriteLine("There is another instance running.");
// Wait for resource
semaphore.WaitOne();
Console.WriteLine("There is now the only instance.");
Console.ReadLine();
}
}
}
}
Wait a second. Didn't I say that wrapping the Semaphore object in a using block would call Close()? Why did I have to explicitly call semaphore.Release()?
The answer to this is Garbage Collection. Sure, Close() will be called (and thus, Release() is called and signals all waiting threads that the resource is available) when the using block exits, but this will only happen when the object is disposed. If you plan to queue up applications (or windows, dialogs, or any other resource), note this signaling behavior.
Code
I've decided to start making code from my blog posts available from a single github repository.
https://github.com/jimschubert/blogs
References
Mastering Node: Addons and FunctionTemplate (uuid.node)
Last night, I pushed an addition to my fork of Mastering Node. I decided to add a bit to the Addons chapter. The first example in this chapter only shows how to add a function to a natively-compiled module (i.e. an addon). This example shows you how to start a module which can be used in the following way:
var Uuid = require('./uuid.node').Uuid;
var uuid = new Uuid();
var myId = uuid.generate();
The project files referenced in the following text can be downloaded from the repo: jimschubert/masteringnode
FunctionTemplate
In v8, a FunctionTemplate is used to create the equivalent to:
var template = function() { }
The function at this point is an object and not an instance of the function.
As an example, we will use the linux package uuid to generate a uuid. We will define the header for this addon as:
dotfiles backup using GitHub
I was recently looking for a solution to backup my configuration files (bash, vim, etc) using GitHub. After some looking around, I've compiled a pretty nice project for myself.
First, this script checks dependencies. My dependencies are git, ruby, vim, tree, rake, gem, bundle, and trash. You could check out the code and add any number of dependencies here. Rubygems and bundler are required because the script later installs all gems listed in Gemfile.
Next, the script copies ~/.bashrc to ~/.bashrc.local. This allows you to keep your current bash configuration as a 'local-only' config that doesn't get copied or committed to github.
The script, as I copied most of bootstrap.sh and the rakefile from @gf3, expects the repository to be cloned to ~/.dotfiles. From there, it calls rake.
Rake looks at every file in ~/.dotfiles and copies the corresponding file relatively from ~/ to, essentially, ~/dotfiles-backup/`date`. I recommend first running the backup to make sure your files are properly backed up.
rake backup
The script then calls 'bundle install' to install all gems. It then copies all files from ~/.dotfiles to replace those relative files that were previously backed up from ~/.
The post-install displays a message to remind you to edit .gitconfig and .hgrc.
Because I've done some copying and compiling, these are relative close to the three projects in the README for right now.
Here is an excerpt from the README:
Bash
$ tree ~/.bash
/home/jim/.bash
├── aliases
├── completions
├── completion_scripts
│ └── git_completion
├── config
├── functions
├── paths
└── prompt
The above files are loaded by .bashrc. The files are pretty self-explanatory, other than prompt which colorizes the bash prompt with tweaks for git.
Cool Aliases
- cd : pushd
- bd : popd
- cd.. | .. : back one directory
- cd... | ... : back two directories
- ^ up to five directories
- rm : trash
- undopush
- ip
- GET | HEAD | POST | PUT | DELETE | TRACE | OPTIONS
Config
- sets editor to vim
- sets English/UTF-8
- sets manpager
- sets commands to ignore in history
- sets noclobber (e.g. prevents
cat > IMPORTANT_FILEmistakes ) - sets nocaseglob (e.g.
ls ~/.B*will list contents of~/.bash)
Functions
The two functions, md and c may not seem like much, but they simplify some commands. For example:
$ md projects; git clone git@github.com:jimschubert/dotfiles.git && cd dotfiles
In the above line, md will create the projects directory and cd into it.
c stands for 'code' and works like this:
jim at computer in ~
$ pwd
/home/jim
jim at computer in ~
$ c dotfiles
~/projects/dotfiles ~
jim at computer in ~/projects/dotfiles on master
$
You can change it to whatever shortcut and issue reload, which is also an alias from this setup.
Screenshot
Notice the color scheme and github branch notifications created by ~/.bash/prompt.
Install nodejs under ChromeOS (CR-48)
Why would I want to do this?
I'm a software developer. I love javascript. I love node.js. I love the direction Google is taking web development, user interaction, and the web in general. Installing node.js opens up a lot of possibilities for me on my CR-48. I don't know if this will work on anything other than the CR-48, considering the machine has to be in developer mode for these instructions.
If you don't have a chromebook yet, or you don't know what they are... where have you been? But seriously, visit http://www.google.com/chromebook/ and check them out.
Before I start, let me first say that following these instructions may void your warranty if you have one, open your machine up to vulnerabilities, or replace existing files and cause instability. If you don't know how to revert or fix any issues that may occur, don't continue. I offer no sort of warranty, support, or anything else. Consider this a 'hack' of sorts.
I found a blog post detailing how to install an archive package and ruby on rails in ChromeOS. I followed part of these instructions and I have modified them to fit my needs.
Prerequisites
- You must have a Chromebook, possibly only the CR-48
- You must be in 'developer mode'
- You must have a writable rootfs (see above link for developer mode)
Instructions
Downloading and installing xz
- Download the xz package
- Enter crosh or VT-2 (CTRL+ALT+T or CTRL+ALT+→)
- If VT-2, login to the shell
- Run on the terminal: cd /home/chronos/user/Downloads
- Run on the terminal: tar -zxf xz-*.tar.gz
- Run on the terminal: cd usr
- Run on the terminal: cp * /usr/
Now that xz is installed in /usr/bin (verify by running on the command line: which xz), you will be able to extract certain files that are necessary for nodejs and possibly any other package you'd like.
Download and install nodejs and openssl.
The site claims openssl is optional, but node wouldn't open without it
- Download nodejs
- Download openssl
- Enter the terminal again and navigate to /home/chronos/user/Downloads
- Run on the terminal: xz -d node*.xz
- Run on the terminal: tar -zxfv openssl*.tar.gz
- Run on the terminal: cd usr
- Run on the terminal: cp * /usr/
Now you should have a working install of nodejs. You can use npm, for instance, to install express and jade.

[c#] Instantiating an object with a private constructor
Not too long ago, I needed to modify a type available in the the BCL which didn't have a public constructor or any method for creating an instance of the object. The solution was to use reflection to invoke the type's private constructor.
Caveat!
Most times, these types are designed with private methods for a reason. There may be internal dependencies which can cause all kinds of problems if they're not met. Only do something like this if you're writing tests against the constructor or exploring the capabilities of Reflection.
The ConstructorInfo Class is the one we'll use. If your constructor is parameterless and non-public, you can instead do:
var myType = (MyType)Activator.CreateInstance(typeof(MyType), true /*nonPublic*/);
To instantiate an object from a non-public constructor with parameters, you'll need three things:
- the target type
- an array of parameter types (same order as signature)
- a reference to the constructor
Suppose your target type is defined as:
class Example
{
public string Display { get; private set; }
private Example(string msg)
{
Display = msg;
}
}
To instantiate this object, you can do the following:
// 1. the target type
var exampleType = typeof(Example);
// 2. an array of parameter types (same order as signature)
var argTypes = new Type[] { typeof(string) };
// 3. a reference to the constructor
// Because method signatures must be unique in parameters and return type,
// this will return the matching constructor, or ctor will be null.
ConstructorInfo ctor = exampleType.GetConstructor(
BindingFlags.Instance | BindingFlags.NonPublic,
null, argTypes, null);
// similar to var example = new Example("You've set me privately!")
var example = (Example)ctor.Invoke(new []{ "You've set me privately!" });
Console.WriteLine("Example's display: {0}", example.Display);
Note:
ConstructorInfo requires FullTrust.





