Skip to content

Commit 01d96df

Browse files
committed
Initial commit.
0 parents  commit 01d96df

File tree

4 files changed

+109
-0
lines changed

4 files changed

+109
-0
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
node_modules

README.md

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# js
2+
3+
**js** is a a better alternative to `node -p`. It will automatically convert data from and to JSON string representations, and will automatically expose enviroment variables as globals preceded with `$`.
4+
5+
## Usage
6+
7+
```bash
8+
js <javascript>
9+
```
10+
11+
## Examples
12+
13+
Using math
14+
15+
```bash
16+
js 2+2
17+
```
18+
19+
Read a field from a JSON file
20+
21+
```bash
22+
js stdin.version < package.json
23+
```
24+
25+
Add a field to a JSON file on the fly
26+
27+
```bash
28+
js 'stdin.foo = "bar", stdin' < in.json > out.json
29+
```

bin/js

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
#!/usr/bin/env node
2+
3+
var fs = require('fs');
4+
var path = require('path');
5+
var program = require('commander');
6+
7+
program
8+
.version(JSON.parse(fs.readFileSync(path.join(__dirname, '../package.json'), 'utf-8')).version)
9+
.usage('<javascript>')
10+
.option('-r, --raw', 'do not attempt to convert data from JSON')
11+
.parse(process.argv);
12+
13+
var stdin = "";
14+
15+
if (!process.stdin.isTTY) {
16+
process.stdin.resume();
17+
process.stdin.setEncoding('utf8');
18+
process.stdin.on('data', function(chunk) {
19+
stdin += chunk;
20+
})
21+
process.stdin.on('end', start);
22+
} else {
23+
start();
24+
}
25+
26+
function start() {
27+
if (!program.raw) {
28+
// attempt to interpret stdin as JSON
29+
try {
30+
stdin = JSON.parse(stdin);
31+
} catch (e) {
32+
// ignore
33+
}
34+
}
35+
36+
// expose environment variables as globals preceded with $
37+
for (var name in process.env) {
38+
var value = process.env[name];
39+
40+
if (!program.raw) {
41+
// attempt to interpret variable as JSON
42+
try {
43+
value = JSON.parse(value);
44+
} catch (e) {
45+
// ignore
46+
}
47+
}
48+
49+
global['$' + name] = value;
50+
}
51+
52+
var result = eval('(' + (program.args.join(' ') || 'undefined') + ')');
53+
54+
if (typeof result == 'string') {
55+
if (result[result.length - 1] != '\n') {
56+
result = result + '\n';
57+
}
58+
} else {
59+
try {
60+
result = JSON.stringify(result, null, 2) + '\n';
61+
} catch (e) {
62+
// ignore
63+
}
64+
}
65+
66+
process.stdout.write(result);
67+
}

package.json

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
{
2+
"name": "js",
3+
"description": "A better `node -p`.",
4+
"author": "Marco Aurelio <[email protected]>",
5+
"version": "0.0.1",
6+
"bin": {
7+
"js": "./bin/js"
8+
},
9+
"dependencies": {
10+
"commander": "~1.1.1"
11+
}
12+
}

0 commit comments

Comments
 (0)