var remark = require('remark');
var visit = require('unist-util-visit');
var remove = require('unist-util-remove');
var program = require('commander');
var fs = require('fs');

function spliterator(code_out) {
  // Our Remark "plugin".
  return function () {
    return function(ast, file) {
      visit(ast, 'code', function (node) {
        code_out.push(node.value);
        remove(ast, node);
      });
    };
  };
}

// Construct the plugin. We'll accumulate the code into `code_chunks` while
// stripping it out of the AST.
var code_chunks = [];
var plugin = spliterator(code_chunks);

program
  .option('-m --markdown <file>', 'markdown output file')
  .option('-c --code <file>', 'code output file')
  .parse(process.argv);

// Process the document.
var processor = remark().use(plugin);
var markdown = processor.process('hello\nfoo\n\n    bar\n\nbaz *qux*');
var code = code_chunks.join('\n') + '\n';

// Output Markdown.
if (program.markdown) {
  fs.writeFile(program.markdown, markdown);
}

// Output extracted code.
if (program.code) {
  fs.writeFile(program.code, code);
}

// If neither is specified, just dump the code to stdout.
if (!program.markdown && !program.code) {
  process.stdout.write(code);
}

@@ -593,16 +593,45 @@
 program%0A
+  .usage('%5Boptions%5D %3Cfile%3E')%0A
   .optio
@@ -755,16 +755,224 @@
 argv);%0A%0A
+// Get the input document.%0Avar infile = program.args%5B0%5D;%0Aif (!infile) %7B%0A  program.help();%0A%7D%0A%0Avar indoc = fs.readFile(infile, function (err, data) %7B%0A  if (err)%0A    throw err;%0A  var indoc = data.toString();%0A%0A  
 // Proce
@@ -984,24 +984,26 @@
 e document.%0A
+  
 var processo
@@ -1028,16 +1028,18 @@
 lugin);%0A
+  
 var mark
@@ -1067,47 +1067,18 @@
 ess(
-'hello%5Cnfoo%5Cn%5Cn    bar%5Cn%5Cnbaz *qux*'
+indoc
 );%0A
+  
 var 
@@ -1116,16 +1116,18 @@
  '%5Cn';%0A%0A
+  
 // Outpu
@@ -1138,16 +1138,18 @@
 rkdown.%0A
+  
 if (prog
@@ -1160,24 +1160,26 @@
 markdown) %7B%0A
+  
   fs.writeFi
@@ -1172,32 +1172,36 @@
     fs.writeFile
+Sync
 (program.markdow
@@ -1214,19 +1214,23 @@
 kdown);%0A
+  
 %7D%0A%0A
+  
 // Outpu
@@ -1247,16 +1247,18 @@
 d code.%0A
+  
 if (prog
@@ -1271,16 +1271,18 @@
 de) %7B%0A  
+ 
+ 
 fs.write
@@ -1285,16 +1285,20 @@
 riteFile
+Sync
 (program
@@ -1311,19 +1311,23 @@
  code);%0A
+  
 %7D%0A%0A
+  
 // If ne
@@ -1376,16 +1376,18 @@
 stdout.%0A
+  
 if (!pro
@@ -1416,24 +1416,26 @@
 ram.code) %7B%0A
+  
   process.st
@@ -1452,10 +1452,16 @@
 (code);%0A
-%7D
+  %7D%0A%7D);
 %0A

Read input Markdown from a file