Permalink
Browse files

added json-urlencode

  • Loading branch information...
1 parent 9883718 commit ce7cc6cc8414568774e54680ec7163832f7b500a @coolaj86 committed Jan 27, 2012
Showing with 128 additions and 0 deletions.
  1. +26 −0 json-urlencode/README.md
  2. +1 −0 json-urlencode/example.json
  3. +84 −0 json-urlencode/index.js
  4. +17 −0 json-urlencode/package.json
View
@@ -0,0 +1,26 @@
+URL Encode JSON
+===
+
+For all the times you want to pass JSON in an HTTP GET (which should be quite rare, btw)
+
+ {
+ "foo":"bar"
+ }
+
+becomes
+
+ %7B%22foo%22%3A%22bar%22%7D
+
+Usage
+---
+
+ json-urlencode example.json
+
+ curl -s http://foobar3000.com/echo/echo.json | json-urlencode
+
+ wget -qO- http://foobar3000.com/echo/echo.json | json-urlencode
+
+Installation
+---
+
+ npm install -g json-urlencode
@@ -0,0 +1 @@
+{"foo":"bar"}
View
@@ -0,0 +1,84 @@
+#!/usr/bin/env node
+(function () {
+ "use strict";
+
+ var fs = require('fs')
+ , filename = process.argv[2]
+ ;
+
+ function printUsage() {
+ console.warn("Usages:");
+ console.warn("json-urlencode path/to/example.json");
+ console.warn("cat path/to/example.json | json-urlencode");
+ console.warn("curl http://foobar3000.com/echo/?urlEncodedJson=`json-urlencode path/to/example.json`");
+ }
+
+ function handleInput(err, text) {
+ var uriEncoded
+ , wrappedInHtml
+ ;
+
+ if (err) {
+ printUsage();
+ return;
+ }
+
+ // We make sure we remove any extra whitespace here
+ uriEncoded = encodeURIComponent(JSON.stringify(JSON.parse(text)));
+
+ console.info(uriEncoded);
+ }
+
+ readInput(handleInput, filename);
+
+ //
+ // this could (and probably should) be its own module
+ //
+ function readInput(cb, filename) {
+
+ function readFile() {
+ fs.readFile(filename, 'utf8', function (err, text) {
+ if (err) {
+ console.error("[ERROR] couldn't read from '" + filename + "':");
+ console.error(err.message);
+ return;
+ }
+
+ cb(err, text);
+ });
+ }
+
+ function readStdin() {
+ var text = ''
+ , timeoutToken
+ , stdin = process.stdin
+ ;
+
+ stdin.resume();
+
+ // how to tell piping vs waiting for user input?
+ timeoutToken = setTimeout(function () {
+ cb(new Error('no stdin data'));
+ stdin.pause();
+ }, 1000);
+
+ stdin.on('data', function (chunk) {
+ clearTimeout(timeoutToken);
+ text += chunk;
+ });
+
+ stdin.on('end', function () {
+ cb(null, text);
+ });
+ }
+
+ if (filename) {
+ readFile();
+ }
+ else {
+ readStdin();
+ }
+
+ }
+
+}());
@@ -0,0 +1,17 @@
+{
+ "author": "AJ ONeal <coolaj86@gmail.com> (http://coolaj86.info)",
+ "name": "json-urlencode",
+ "description": "A commandline utility to urlencode JSON files",
+ "version": "1.0.0",
+ "main": "index.js",
+ "bin": {
+ "json-urlencode": "./index.js"
+ },
+ "engines": {
+ "node": ">= 0.2.0"
+ },
+ "test": ["cat example.json | node index.js", "node index.js example.json"],
+ "dependencies": {},
+ "devDependencies": {},
+ "preferGlobal": true
+}

0 comments on commit ce7cc6c

Please sign in to comment.