npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

serialize-function

v2.0.3

Published

Serializes javascript functions to a JSON-friendly format

Readme

serialize-function

ci status Node.js supported and tested on v22 through v26 ECMAScript standard supported as of ES2023

npm


Quickstart

Supports both CommonJS and ES Modules:

const { serialize, deserialize } = require('serialize-function');
// or
import { serialize, deserialize } from 'serialize-function';

Serializes javascript functions to a JSON-encodable object suitable for storage to file or transfer over the wire:

function doTheThing(a,b,c,d,e) { return a + b * c / d % e; }

const obj = await serialize(doTheThing);
console.log(obj);
// {
//   params: [ 'a', 'b', 'c', 'd', 'e' ],
//   body: 'return a + b * c / d % e;',
//   type: 'Function'
// }

Deserializes back into an invokable function:

const func = await deserialize(obj);
console.log( func(1, 2, 3, 4, 5) );
// 2.5

Deep serialization

You may want to deeply serialize any functions nested at arbitrary levels of your data structures. The provided convenience functions will traverse and selectively clone any containing objects, while serializing any functions found:

const { deepSerialize, deepDeserialize } = require('serialize-function');

const original = {
  foo: () => 'something',
  bar: [
    function* (seed = 0) { let n = seed; while(true) { n = n * 2; yield n; } }
  ],
  baz: new Date('2026-01-01')
}

const clone = await deepSerialize(original);
// {
//   foo: {
//     params: [],
//     body: "return ('something');",
//     type: 'ArrowFunction'
//   },
//   bar: [
//     {
//       params: [ 'seed = 0' ],
//       body: 'let n = seed; while(true) { n = n * 2; yield n; }',
//       type: 'Generator'
//     }
//   ],
//   baz: 2026-01-01T00:00:00.000Z
// }

// original container and functions remain unmodified
original.foo(); // 'something'
const gen1 = original.bar[0](3.14);
gen1.next().value; // 6.28
gen1.next().value; // 12.56

const restored = await deepDeserialize(clone);
// {
//   foo: [Function: anonymous],
//   bar: [ [GeneratorFunction: anonymous] ],
//   baz: 2026-01-01T00:00:00.000Z
// }

// deserialized functions remain invokable
restored.foo(); // 'something'
const gen2 = restored.bar[0](901364);
gen2.next().value; // 1802728
gen2.next().value; // 3605456

Hashing

Optionally supports SHA256 checksum hashing to prevent MITM tampering:

const hashedObj = await serialize(doTheThing, { hash: true });
console.log(hashedObj);
// {
//   params: [ 'a', 'b', 'c', 'd', 'e' ],
//   body: 'return a + b * c / d % e;',
//   type: 'Function',
//   hash: '814fab043d5bcee7a589b1d73a9fb42a2d716c3f615056c41a062478e7844827'
// }

hashedObj.body = 'return doSomethingMalicious(...arguments);';
const tamperedFunc = await deserialize(hashedObj, { hash: true });
// ChecksumError: Checksum failed

Under the hood, hashing uses the SubtleCrypto API.

Whitespace and comments

Line breaks within the function body are preserved and normalized, but all other padding whitespace is removed from the function by default, along with any comments.

You can optionally preserve either or both, with the corresponding options:

function thingNumberTwo(
  /* marco */
  a,   b,	c,
  d,e/* polo */
) {
  // add some things
  const sum = a + b;

  /* multiply by another thing */
  const product = sum * c;

  // divide by _another_
  // different thing
  const quotient = product / d;
  /*
    and modulus THAT thing
  */
  const remainder = quotient % e;
  return remainder;
}

const commentedObj = await serialize(thingNumberTwo, { whitespace: true, comments: true });
console.log(commentedObj);
// {
//   params: [ '\n  /* marco */\n  a', '   b', '\tc', '\n  d', 'e/* polo */\n' ],
//   body: '\n' +
//     '  // add some things\n' +
//     '  const sum = a + b;\n' +
//     '\n' +
//     '  /* multiply by another thing */\n' +
//     '  const product = sum * c;\n' +
//     '\n' +
//     '  // divide by _another_\n' +
//     '  // different thing\n' +
//     '  const quotient = product / d;\n' +
//     '  /*\n' +
//     '    and modulus THAT thing\n' +
//     '  */\n' +
//     '  const remainder = quotient % e;\n' +
//     '  return remainder;\n',
//   type: 'Function'
// }

Function type support

Arrow functions, generators, and all async variants are supported (contingent on browser support where relevant):

await serialize(
  (i,j,k) => ({ i, j, k })
);
// {
//   params: [ 'i', 'j', 'k' ],
//   body: 'return (({ i, j, k }));',
//   type: 'ArrowFunction'
// }

await serialize(
  function* (x,y,z) {
    yield x;
    yield y;
    yield z;
  }
);
// {
//   params: [ 'x', 'y', 'z' ],
//   body: 'yield x;\nyield y;\nyield z;',
//   type: 'Generator'
// }

await serialize(
  async (ms) => new Promise( 
    resolve => setTimeout(resolve, ms)
  )
);
// {
//   params: [ 'ms' ],
//   body: 'return (new Promise(\nresolve => setTimeout(resolve, ms)\n));',
//   type: 'AsyncArrowFunction'
// }

[!NOTE] As there is no global Class object constructor, there is no way to safely deserialize ES6 classes.

As such, ES6 classes are not currently supported for serialization.

Alternatively, you can rewrite your classes as functions, or transpile them with tools like Babel.

Changelog

Any potentially breaking changes will be documented here.

  • 1.1.0 - Standardized both node and web builds on SubtleCrypto API
  • 1.2.0 - Refactored comment stripping, to address potential regex DOS
  • 2.0.0
    • Made all exported functions fully async
    • Implemented named captures for format patterns
    • Implemented deep de/serialization