core.js helps you create scalable applications written in JavaScript, giving you structure and patterns needed to keep everything separated, have loading, saving, replaying events and logging.
core is a concept introduced by Nicholas C. Zakas in this video
Conceptually, everything in your application is a module, and your modules should work independently from each other, so if one module breaks, the others should not.
The central piece is the core.
A module should never talks directly to another module, for that you use a combination of listeners and notifications.
So let's think about the twitter page, and how we could re-build it using the core concept
Everything inside a red square is a module, they work independently.
npm i @eroc/core
Raw import
import { createCore, ALL, ERROR } from "./node_modules/@eroc/core/dist/core.es.js";
With Node.js, rollup, webpack or parcel
import { createCore, ALL, ERROR } from "@eroc/core";
With old Node.js or Browserify
const { createCore, ALL, ERROR } = require("@eroc/core/dist/core.umd.cjs");
With Deno
import { createCore } from "https://unpkg.com/@eroc/core/dist/core.es.js";
A module exports start.
export { start, stop };
const start = function (emitter) {
return {};
};
A module may export a stop function.
Optional:
- stop
- getState
- restoreState
const stop = function (startReturn) {
// this allows to close open files, sockets, etc
};
const restoreState = function (startReturn, state) {
// do what is necessary to restore sate
};
const getState = function (startReturn) {
// return the current state
// for example in a drawing application , all the coordinates and shapes drawn
};
To start this module in your core file:
import { createCore } from "@eroc/core";
import * as exampleModule from "./exampleModule.js";
const core = createCore();
core.start(exampleModule);
Modules can only communicate via messages with other modules with the emitter received when start is called. It guarantees that if a module tries to call something that doesn't exists or is broken, it won't break the module itself.
emitter.on(EVENT_NAME, function (data) {
});
emitter.emit(EVENT_NAME, { a: 7 });
To avoid spelling mistakes, import event names from a common file called eventNames.js.
To stop a module use the method core.stop()
.
const exampleId = core.start(exampleModule);
core.stop(exampleId);
When you stop a module, the function stop
will be called, if it exists.
Now, thinking about Twitter, every time you tweet something, it should appear on your tweet list right? But since our modules don't talk directly to each other, let's use the emitter.
Our tweet
module should notify other modules that something has happened.
export { start };
import { NEW_TWEET } from "./eventNames.js";
const start = function(emitter) {
// For the sake of simplicity, use an interval
setInterval(function() {
emitter.emit(NEW_TWEET, {
author: `Mauricio Soares`,
text: `core is pretty #cool`
});
}, 5 * 1000)
};
Every 5 seconds, this module notifies everything that is listening to NEW_TWEET
that something has happened. If nothing is listening to it, then nothing happens.
Our tweet-list
is going to listen for this notifications.
export { start };
import { NEW_TWEET } from "./eventNames.js";
const start = function (emitter) {
emitter.on(NEW_TWEET, (data) => {
// do something with the data
});
};
Cool right? If one of those modules stop working, then it will not break the other one!
Returns a new instance of core.
module
The module as a name-space (import * as exampleModule from "./exampleModule.js"
)options
optional object- name optional, String or Symbol that becomes moduleInstanceId
- data optional, will be passed as second argument to the start function of the module
- worker optional, if true the module will be inside a worker see 4.1.0 limitations
- workerReady, mark as true if the url has code prepared with storeWorkerCodeFromIIFEFile or prepareWorkerCode
returns a promise that resolves with moduleInstanceId that can later be used to stop the module
const exampleInstanceId = await core.start(exampleModule);
await core.stop(exampleInstanceId);
Constant to listen to all events
// listen for all events
core.on(ALL, ({ name, data, time }) => {
const timeString = new Date(time).toISOString();
console.debug(`${timeString} event ${String(name)} with data`, data);
});
Constant to listen to most errors
// listen for errors
core.on(ERROR, ({ time, phase, error }) => {
const timeString = new Date(time).toISOString();
console.error(`Error during phase ${phase} at ${timeString}`, error);
});
Optional logging to get started
import { createCore, useDefaultLogging } from "@eroc/core";
const core = createCore();
// listen for all events
useDefaultLogging(core);
Utility to record all events. example
returns an eventRecording. Access eventRecording.events
to view all past events.
stops an eventRecording.
import { createCore, useDefaultLogging } from "@eroc/core";
const core = createCore();
let eventRecording = startEventRecorder(core);
stopEventRecorder(core, eventRecording);
Helper to replay events.
Will replay previousEvents on core. previousEvents could come from eventRecording.events
or from a database. Make sure to initialize modules before, for it to have any effect. While events are replayed regular event emits are disabled. This avoids duplicated events in case you emit events as a consequence of another event.
import { createCore, replayEvents } from "@eroc/core";
const core = createCore();
// ... initialize modules
const events = // get events
replayEvents(core, events, { sameSpeed: true });
ReplayEvents might not be possible past a certain limit. That is why you may want to implement a state restoring mechanism.
Expects an object with keys being modules names and values being the state to restore. Modules need a restoreState
function for this to have any effect.
Returns all states. Resolved value is the same shape as what core.restoreAllStates
expects. Has no effect for modules that do not define a getState
function.
Ideally neither restoreAllState nor eventPlayer are used alone to load a given state. EventPlayer alone would require to store all events from the beginning and replaying them 1 by one which can take huge overhead in both memory and time. And restoreAll state would lose precision, because not every state is saved. So the ideal is to periodically save state and capture the events from there on.
import {prepareWorkerCode, storeWorkerCodeFromIIFEFile} from "@eroc/core";
// source has to be an IIFE that exposes start and stop
const source = "./examples/gameOfLife/gameOfLife.js";
const destination = "./examples/gameOfLife/gameOfLifeWorkerReady.js";
storeWorkerCodeFromIIFEFile(source, destination);
This code can then be used with the workerReady option
- Mauricio Soares - https://github.com/mauriciosoares
- GrosSacASac
- Fork core
- Create a topic branch -
git checkout -b my_branch
- Change some files and git commit
- Push to your branch -
git push origin my_branch
- Send a Pull Request
You need NodeJS installed on your machine
npm i
npm run bundle
npm t
- core.js and prepareWorkerCode.js export a function prepareWorkerCode
- prepareWorkerCode.js exports a function storeWorkerCodeFromIIFEFile
- Modules inside worker can use restoreState and getState
- Modules without imports and export, without restoreState and getState can run inside worker
- Core class is replaced with createCore function
- The default logger no longer displays the time (you can create your own logger)
- replayEvents returns a promise
- more compact logging
- core.start accepts addition named data parameter that will be passed to the start function as second argument
- Add optional getState and restoreState function as part as a module
- Add getState to the core
- Add getAllStates to the core
- Add restoreState to the core
- Add restoreAllStates to the core
- Use abstract name to import for dependencies. Change default main. Convert to ES module.
- Rename dist/core.umd.js into dist/core.umd.cjs
- Add default logger
- eventPlayer, eventRecorder extras are importable directly from the core
- core.start, core.stop return Promises
- the module start and stop can return a promise
- errors are emitted