1 | #!/usr/bin/env node
|
2 |
|
3 | var optimist = require('optimist')
|
4 | var map = require('map-async')
|
5 | var open = require('opener')
|
6 | var path = require('path')
|
7 | var http = require('http')
|
8 | var electrify = require('../')
|
9 | var fs = require('fs')
|
10 | var bl = require('bl')
|
11 | var btoa = require('btoa')
|
12 | var marked = require('marked')
|
13 |
|
14 | var readme = fs.readFileSync(__dirname + '/../README.md', 'utf8')
|
15 | var button = fs.readFileSync(__dirname + '/../img/fork.png')
|
16 |
|
17 | button = btoa(button)
|
18 | button = 'data:image/png;base64,' + button
|
19 |
|
20 | var argv = optimist
|
21 | .wrap(70)
|
22 | .usage('$0 [bundle(s)...] {options}')
|
23 |
|
24 | .alias('h', 'help')
|
25 | .describe('h', 'Displays these instructions.')
|
26 |
|
27 | .alias('o', 'output')
|
28 | .describe('o', 'Output path of the bundle. Defaults to stdout.')
|
29 |
|
30 | .alias('O', 'open')
|
31 | .describe('O', 'Opens electrify in a new browser window automatically')
|
32 |
|
33 | .alias('m', 'mode')
|
34 | .describe('m', 'the default file scale mode to display: should be either "count" or "size". Default: size')
|
35 |
|
36 | .argv
|
37 |
|
38 | if (argv.help) {
|
39 | optimist.showHelp()
|
40 | return process.exit(1)
|
41 | }
|
42 |
|
43 | var files = argv._ || []
|
44 |
|
45 | files = Array.isArray(files)
|
46 | ? files
|
47 | : files ? [files] : []
|
48 |
|
49 | if (!files.length) {
|
50 | process.stdin.resume()
|
51 | process.stdin.pipe(bl(function(err, data) {
|
52 | if (err) throw err
|
53 | handle([data])
|
54 | }))
|
55 | } else {
|
56 | map(files, function(file, next) {
|
57 | fs.readFile(path.resolve(file), next)
|
58 | }, function(err, files) {
|
59 | handle(files)
|
60 | })
|
61 | }
|
62 |
|
63 | function handle(bundles) {
|
64 | electrify.bundle(bundles, {
|
65 | mode: argv.mode,
|
66 | footer: marked(readme),
|
67 | header: [
|
68 | '<a href="https://github.com/electrode-io/electrify">',
|
69 | '<img style="position:absolute;top:-8px;left:-8px;border:0;"',
|
70 | 'src="' + button + '"',
|
71 | 'alt="Fork me on GitHub"',
|
72 | '></a>'
|
73 | ].join(' ')
|
74 | }, function(err, html) {
|
75 | if (err) throw err
|
76 | if (argv.output) return fs.writeFileSync(argv.output, html)
|
77 | if (!argv.open) return console.log(html)
|
78 |
|
79 | // Create a temporary HTTP server, serve up
|
80 | // the index.html page and then close the
|
81 | // process ASAP
|
82 | var server = http.createServer()
|
83 |
|
84 | server.on('request', function(req, res) {
|
85 | if (req.url === '/favicon.ico') {
|
86 | return res.end('missing') // PRs welcome :)
|
87 | }
|
88 |
|
89 | res.once('finish', function() {
|
90 | setTimeout(function() {
|
91 | process.exit()
|
92 | }, 500)
|
93 | })
|
94 |
|
95 | res.setHeader('content-type', 'text/html')
|
96 | res.end(html)
|
97 | }).listen(4000, function(err) {
|
98 | if (err) throw err
|
99 | open('http://localhost:4000/')
|
100 | })
|
101 | })
|
102 | }
|