-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
executable file
·83 lines (55 loc) · 1.67 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/usr/bin/env node
/**
* Module dependencies.
*/
var program = require('commander');
var ejs = require('ejs');
var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
program
.version('1.0.0')
.option('-j, --json [path]', 'Provide a JSON string or a path to a JSON file.', undefined)
.option('-d, --destination [path]', 'Path to output destination. If none is provided, output will be piped to stdout.', undefined)
.parse(process.argv);
var input = '';
var output = '';
var options = {};
read();
function read(){
if(program.args.length){
input = fs.readFileSync( path.join( process.cwd(), program.args[0] ), {encoding:'utf-8'} );
write();
}else{
// resume and set the encoding of stdin stream
process.stdin.resume();
process.stdin.setEncoding('utf-8');
// set our read stream to stdin
process.stdin.on('data', function(data){ input += data });
process.stdin.on('end', function(){ write(); });
}
}
function write(){
if(program.json){
try{
json = fs.readFileSync( path.join( process.cwd(), program.json ), {encoding:'utf-8'} )
}catch(e){
json = program.json;
}
options = JSON.parse(json);
}
// add filename option - necessary to allow ejs <% include %>
options.filename = program.args[0];
// render the ejs with supplied options
output = ejs.render( input, options );
// if a destination option is provided, write the output to a file
if( program.destination ){
var file = path.join( process.cwd(), program.destination );
mkdirp.sync(path.dirname( file ));
fs.writeFileSync( file, output );
}else{
// write the output to stdout
process.stdout.write( output );
process.exit();
}
}