Skip to content

Reusable Custom Functions With .fxrc.js ​

When you keep typing the same arrow functions into fx, move them into a .fxrc.js file and call them by name. Every function defined there is available in every fx argument. If you don't have fx yet, install fx.

Where fx Looks for .fxrc.js ​

fx loads every one of these files that exists, in this order, and combines them:

  1. ./.fxrc.js — the current working directory
  2. ~/.fxrc.js — your home directory
  3. $XDG_CONFIG_HOME/fx/.fxrc.js — defaults to ~/.config/fx/.fxrc.js
  4. fx/.fxrc.js inside each directory of $XDG_CONFIG_DIRS — defaults to /etc/xdg/fx/.fxrc.js

The file is plain JavaScript. There is no export: top-level functions and variables become globals, just like the built-in functions.

Define and Call a Simple Function ​

Put a function in .fxrc.js:

js
function addOne(x) {
  return x + 1
}

Pass its name as an argument. fx calls it with the current value:

bash
echo '1' | fx addOne

It prints 2. It chains with other arguments like any function: fx users.json '.[0].orders' addOne prints 13 for this users.json, which the rest of the examples use:

json
[
  {"id": 1, "name": "Alice", "email": "alice@example.com", "status": "active", "role": "admin", "orders": 12},
  {"id": 2, "name": "Bob", "email": "bob@example.com", "status": "inactive", "role": "user", "orders": 3},
  {"id": 3, "name": "Carol", "email": "carol@example.com", "status": "active", "role": "user", "orders": 7},
  {"id": 4, "name": "Dave", "email": "dave@example.com", "status": "active", "role": "admin", "orders": 0}
]

Custom Functions With Arguments ​

To make a helper take arguments, have it return a function. This is how built-ins like sortBy(fn) and map(fn) work too.

js
// pluck('name') -> array of names
function pluck(key) {
  return arr => arr.map(x => x[key])
}

// where({status: 'active'}) -> objects where every given field matches
function where(query) {
  return arr => arr.filter(x =>
    Object.entries(query).every(([k, v]) => x[k] === v)
  )
}
bash
fx users.json "where({status: 'active'})" "pluck('name')"
json
[
  "Alice",
  "Carol",
  "Dave"
]

Sum and Average JSON Values ​

js
function sum(arr) {
  return arr.reduce((a, b) => a + b, 0)
}

function avg(arr) {
  return arr.length ? sum(arr) / arr.length : 0
}
bash
fx users.json "pluck('orders')" sum
22

@.orders works just as well as pluck: fx users.json '@.orders' avg prints 5.5.

Pick or Omit Keys From JSON Objects ​

js
function pick(...keys) {
  return obj => Object.fromEntries(keys.filter(k => k in obj).map(k => [k, obj[k]]))
}

function omit(...keys) {
  return obj => Object.fromEntries(Object.entries(obj).filter(([k]) => !keys.includes(k)))
}

Use them on one object, or on every element with map:

bash
fx users.json '.[0]' "omit('email', 'orders')"
json
{
  "id": 1,
  "name": "Alice",
  "status": "active",
  "role": "admin"
}
bash
fx users.json "map(pick('id', 'name'))"
json
[
  { "id": 1, "name": "Alice" },
  { "id": 2, "name": "Bob" },
  { "id": 3, "name": "Carol" },
  { "id": 4, "name": "Dave" }
]

Convert JSON to CSV With a Custom Function ​

When a function returns a string, fx prints it without quotes, so you can redirect it straight to a file.

js
function toCSV(arr) {
  const cols = Object.keys(arr[0])
  const esc = v => {
    const s = v == null ? '' : String(v)
    return /[",\n]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s
  }
  return [cols.join(','), ...arr.map(r => cols.map(c => esc(r[c])).join(','))].join('\n')
}
bash
fx users.json "map(pick('name', 'role', 'orders'))" toCSV > users.csv
name,role,orders
Alice,admin,12
Bob,user,3
Carol,user,7
Dave,admin,0
js
function table(arr) {
  if (!Array.isArray(arr)) throw new Error('table: expected an array, got ' + typeof arr)
  const cols = Object.keys(arr[0])
  const rows = arr.map(r => cols.map(c => String(r[c] ?? '')))
  const widths = cols.map((c, i) => Math.max(c.length, ...rows.map(r => r[i].length)))
  const line = cells => cells.map((s, i) => s.padEnd(widths[i])).join('  ').trimEnd()
  return [line(cols), line(widths.map(w => '-'.repeat(w))), ...rows.map(line)].join('\n')
}
bash
fx users.json 'sortBy(x => -x.orders)' "map(pick('name', 'orders'))" table
name   orders
-----  ------
Alice  12
Carol  7
Bob    3
Dave   0

Project-Local vs Global .fxrc.js ​

Keep general-purpose helpers (sum, pick, table) in ~/.fxrc.js or ~/.config/fx/.fxrc.js so they work everywhere. Put helpers that only make sense for one project's data in .fxrc.js at that project's root and run fx from there; they are loaded in addition to the global ones.

WARNING

All files are joined into one script, with the current directory's file first. If both files declare function greet, the one declared last wins, so the global definition overrides the local one. If both declare const greet, fx fails with SyntaxError: Identifier 'greet' has already been declared. Give project-specific helpers their own names.

Debug Errors in .fxrc.js ​

A syntax error in .fxrc.js breaks every fx command that runs JavaScript, even a bare fx data.json len, and the message does not name the file:

bash
echo '[1,2,3]' | fx sum
Unexpected end of input

With Node.js installed, node --check .fxrc.js reports the file and line. Line numbers in fx's own messages count from the start of fx's built-in library, not your file.

Runtime errors point at the argument that called the helper:

bash
echo '{"users": []}' | fx table
  table
  ^^^^^

Error: table: expected an array, got object

A ReferenceError: pluck is not defined means fx didn't load the file: run fx from the directory that contains it, or move it into your home directory. To inspect values inside a helper, add console.log(...). Its output goes to stdout alongside the result, so remove it when you're done.

See Also ​