Permalink
Browse files

Separate command line and non-command line code.

For copy-json.js
Address #7
  • Loading branch information...
racheltstevens
racheltstevens committed Feb 24, 2017
1 parent 16690d6 commit befbe5edbf6f747b445fd9eb5a45aaf5f9a94edc
Showing with 34 additions and 26 deletions.
  1. +11 −0 bin/copy-json.js
  2. +23 −26 lib/copy-json.js
@@ -0,0 +1,11 @@
'use strict';
const copyJson = require('../lib/copy-json.js');

const stdin = '/dev/stdin';
const stdout = '/dev/stdout';

let inFile = process.argv[2] === '-' ? stdin : process.argv[2];
let outFile = process.argv[3] ? process.argv[3] : stdout;
let outFileFlag = outFile === stdout ? 'a' : 'w';

copyJson(inFile, outFile, outFileFlag);
@@ -2,35 +2,32 @@

const fs = require('fs');

const stdin = '/dev/stdin';
const stdout = '/dev/stdout';

let inFile = process.argv[2] === '-' ? stdin : process.argv[2];
let outFile = process.argv[3] ? process.argv[3] : stdout;
let outFileFlag = outFile === stdout ? 'a' : 'w';

fs.readFile(inFile, { encoding: 'utf8' }, (error, data) => {
let json, pojo;
if (error) {
console.error(error.stack);
return;
}

try {
pojo = JSON.parse(data);
} catch (error) {
console.error(error.stack);
return;
}

json = JSON.stringify(pojo, null, 2);

fs.writeFile(outFile, json, { flag: outFileFlag }, error => {
const copyJson = function (inFile, outFile, outFileFlag) {
fs.readFile(inFile, { encoding: 'utf8' }, (error, data) => {
let json, pojo;
if (error) {
console.error(error.stack);
return;
}

console.error('\ncopied');
try {
pojo = JSON.parse(data);
} catch (error) {
console.error(error.stack);
return;
}

json = JSON.stringify(pojo, null, 2);

fs.writeFile(outFile, json, { flag: outFileFlag }, error => {
if (error) {
console.error(error.stack);
return;
}

console.error('\ncopied');
});
});
});
};

module.exports = copyJson;

0 comments on commit befbe5e

Please sign in to comment.