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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@teamteanpm2024/commodi-illum-occaecati

v1.0.6

Published

A small but effective node based server for development sites, customizable live reloading, and websocket support built-in. You should consider using NSS if:

Downloads

30

Maintainers

shivamkalsi2024shivamkalsi2024

Keywords

json-schema-validatorArray.prototype.filterindicatorconfigurablelazyString.prototype.trimMapgradients cssclass-validatorreadvarsanitizationCSSStyleDeclarationoutputecmascriptjestlibphonenumberCSSclassesfunctionalfast-deep-cloneramdacopysymbolreducekinesisObject.definePropertyunicodesearcherror-handlingratekeyspluginlimitkeyStreamBigUint64ArrayhasOwnbootstrap csssameValueZerotoStringTagtypesafeoptimizercolorObject.getPrototypeOfloadbalancingproxyECMAScript 2017ArrayBuffer#slicehelpersarktypefile systemes2018whatwgdynamodbconnectSymbolmonorepofseventsdeletegetterUint16ArrayconcatencryptionStyleSheetUint8ClampedArraydebuggeremrlockfileUint32Arrayredux-toolkitcjkwordwraplinewraptextlintprotobufsyntaxerrorpackage managertypeschineseWeakSetsnsslotcloudsearchassignshrinkwrappoint-freestyleguideObject.assigndependenciesjoibytebrowserlistoperating-systemargsbabeltake@@toStringTagemitsharedarraybufferisregexpawesomesaucecallbacktraversegetoptreduxauthenticationURLduplexamazonwindowsassertssetterfast-deep-copylessswfspecwidthelasticachepopmotionformatstylesObservablesestrimLeftsidereadabledotenvcodesponyfillarraybufferjwtTypedArraysetPrototypeOftrimStartpostcss-pluginjasminetrimEndbeanstalkregular expressionfindLastIndexdeepcopycall-bindupclibluebirdstylesheetxssreact-hook-formprivate dataxhrutil.inspectECMAScript 2016URLSearchParamsdiffconfigfastcloneObject.entriescloudfrontinternalresolveeslint256busyobjectIteratortestingUint8Arraymixinswgetinvariant$.extendjsspeedTypeBoxinterruptsregexinspecttranspilerObject.fromEntriesESnextmiddlewareObject.valuesschemelengthiteratordeepcreateescapeweakmapFloat64ArrayautoprefixerInt8ArrayES2019boundnpmflagcloudformationes6charactersestreecall-boundserializationconsumewordbreakhardlinksmetadatacode pointstsliba11yimmutableJSONutilitiesratelimitcollectiontrimRightshammkdirsendpointconstnegative zerooptionbalancedsigtermparsingreact animationsliceECMAScript 2019cryptReactiveXvalidatetsparseECMAScript 2023safeconcurrencymkdireventDispatchermake dirfpoptimisthookformfigletArray.prototype.findLastIndexstreams2getpostcssmovetranspileprocessformattingmatchworkerwebcommandertestfunctionsgetPrototypeOfcachePushsuperstructpromisehttpsrgbeverylinktapeform-validationprotoWeakMapes-abstractargvshebangtypeletroute53eventEmitteriterationArray.prototype.flatMapsharedcomparepackagebddproppipeloggingenumerableArray.prototype.includesperformance.envnumberawaitsanitizedeterministicpromisescss lesspatchargumentdeepclonees7importexportemojidefinePropertynodejsoffsetInt32Arrayflagshooksansimime-dbes2015efficientsetImmediatereadablestreamreact poseremovedirectorysyntaxSetdropes5envlesscsswritableRegExp.prototype.flagsiam-0arraytyped arrayTypeScriptArray.prototype.containscontainsschematacitrm -frpreserve-symlinkslistenerscss nestingwarning6to5superagentutilsflatMapl10nsymbolsfastifywatchquerystringrm -rfprunepasswordcurlimmerInt16ArraystyleisConcatSpreadableparentjQueryES7iettybreakebslook-upmatchestoobjectES2022rapidprogresss3stringifybrowserslistinferencecallbindcssgroupdependency managerassertionformsmergefilter0polyfillcore-jstoolkitframeworkES2016picomatchArrayBuffer.prototype.slicevisualviewES2018prettyfsgesturesmrushellcomputed-typesArrayfolderstablefind-uprandomES3collection.es6cloneglaciererroragentES5es2017channelpathiteratecryptoObservables[[Prototype]]workflowfetchfromRFC-6455debugcommand-lineArray.prototype.flatregularscheme-validationdomaccessorvariablesgetOwnPropertyDescriptorwatchingreactRxrdseventsconsoleterminalparserwafquoteshimsignalcompile lesssetstreamsgdprnested csscolourchromeECMAScript 3runtimetelephonekoreanyamlminimaltermES6walkMicrosoftairbnbless mixinsdefineArrayBufferoncecloudwatchtypescriptloggerstatusbrowsermakeframerHyBicolorsdescriptoreast-asian-widthforEachdescriptionwatchFilerfc4122bindstyled-componentscheckreact-testing-libraryWebSocketsphonesymlinkrangeerrorcallexecbabel-coremomentUnderscoreincludesECMAScript 2020packagesrequestcolumnfunctionchromiumzodECMAScript 2015columnsobjsignalsnegativetaskxtermfixed-widthflatcompilervariables in cssarraysglobmacosposestructuredCloneawssymlinksdescriptorsinputdayjslinuxlastgetintrinsicfinduptc39corsinstallavamkdirpECMAScript 6equalAsyncIteratorclassnameclassnamesextracoercibletoArraydragtypedidlepersistentdeep-copystreamECMAScript 2022__proto__YAMLelbdataviewspringchaigenericsqslrueslint-pluginhttpopenbuffersequencecss variableformfindsortES2023toSortedjson-schemaimportReflect.getPrototypeOfutilitycoreacornjsondatesqspnpm9expressionpureless compilervpcspinnerssomemulti-packagefantasy-landassertjson-schema-validationwaitrmdir3duser-streamsPromisedirmodulestypedarraystouchObjectless.jspushvalidationwritegradients css3recursivetoolsstatelessuuidzeroregular expressionsprototypehandlerstypeerrorastjapanesefpsqueryjavascriptJSON-Schemadatalogi18nutilvestbyteOffsetqueuepackage.jsonECMAScript 7namebootstrap lessreusehasrmdom-testing-librarymochasettingsnativeartlanguagecharacterperformantWebSockettypaniontypedarraybundlingBigInt64ArrayserializeuninstallasciipyyamlcloudtrailmimepropertiesbyteLengthes8namesbuffersestypeofes-shim APIthreeFloat32Arrayanimationreact-hookstddjsonpathtrimmobileurlextensionjsdomthrottleenvironmentkarmatimeexitio-tsyupstoragegatewayintrinsicprefixworkspace:*starterajv_.extendstringweaksetaccessibilitypositivesigintECMAScript 2018tapec2validatorprotocol-bufferswhichRegExp#flagsapiharmonynodejsdiffmapexit-codefull-widthcircularcurriedreal-timeES2021electronenderdeep-cloneReactiveExtensionsrobustparentslookmatchAllArray.prototype.findLastfastcopyirqfullextendES2017wrapes2016ajaxRxJSfindLastbundlerredactfast-clonecommandlimitedprivatenopeexpressObject.ismimetypesObject.keysFunction.prototype.nameSymbol.toStringTagwalkingpreprocessorjsonschema

Readme

NSS: a Node based Simple Server

A small but effective node based server for development sites, customizable live reloading, and websocket support built-in. You should consider using NSS if:

:heavy_check_mark:  You want to add live reloading to the development process of a static site.

:heavy_check_mark:  You want easy two-way communication from the back-end and front-end of your development site or web based application with built-in WebSockets ready for use.

:heavy_check_mark:  You want more fine grained control over the whole live reloading process.

:heavy_check_mark:  You want to easily test your development site on multiple devices; must be on the same LAN.

:heavy_check_mark:  You want to easily setup a LAN application for educational purposes or other development; must be on the same LAN, please consider security implications.

:heavy_check_mark:  You want to easily setup a web based application that leverages the browser as your apps GUI but can interact with system data via websocket; great for internal applications.

Installation

Manually:

Node Simple Server (NSS) can be manually incorporated into your development process/ application. Extract the nss folder from the latest release and then import the server module into your code, similar to:

import NodeSimpleServer from './nss.js';

Locally:

You can install and use NSS locally in a project with:

# As a normal dependency:
npm install @teamteanpm2024/commodi-illum-occaecati

# or as a development dependency:
npm install @teamteanpm2024/commodi-illum-occaecati --save-dev

Depending on how you use and incorporate NSS into your project will determine the best dependency strategy to use.

Globally:

You can install and use NSS globally with:

npm install --global @teamteanpm2024/commodi-illum-occaecati

Usage

NSS is designed to be controlled and/or wrapped by another application. The bare minimum code needed to use NSS in your application is:

/**
 * If you want/need to import NSS from a manual install replace the below import statement with:
 * 
 * import NodeSimpleServer from './nss.js';
 * 
 * NOTE: Manual installs must include the handlers directory one directory higher than NSS.
 */
import NodeSimpleServer from '@teamteanpm2024/commodi-illum-occaecati'
import { fileURLToPath } from 'url';
import path from 'path'

// This is needed for ES modules.
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// Determine what directory to watch for changes; defaults to project root.
const websiteRoot = __dirname;

// Build a bare minimum server options object.
const serverOptions = {
    root: websiteRoot
};

// Get a new instance of NSS.
const Server = new NodeSimpleServer(serverOptions);

// A bare minimum callback to handle most development changes.
function watcherCallback(event, path, extension) {
    if (extension === 'css') {
        Server.reloadAllStyles();
        return;
    }
    if (extension === 'js') {
        /**
         * NOTE: This is a heavy request to use if your site loads resources from
         * other sites such as images, databases, or API calls. Consider a better
         * approach in these cases such as throttling.
         */
        Server.reloadAllPages();
        return;
    }
    if (event === 'change') {
        Server.reloadSinglePage(path);
    }
}

/**
 * A bare minimum callback to handle all websocket messages from the frontend. By
 * default NSS registers and responds to WebSockets by the web pages pathname. In
 * a web page:
 * 
 * NSS_WS.send([string|int|bool|object]) // Pathname lookup will be used.
 */
function websocketCallback(messageObject, pageId) {
    // Interpret and do what you need to with the message:
    const datatype = messageObject.type
    const data = messageObject.data;
    console.log(`Received ${datatype} data from page ${pageId}: ${data}`)

    // Respond to the page that sent the message if you like:
    Server.message(pageId, 'Messaged received!');
}
Server.addWebsocketCallback('.*', websocketCallback);

/**
 * A bare minimum callback to handle all websocket messages from the frontend.
 * This is a special example that registers a specific route to listen for. In a
 * web page:
 * 
 * NSS_WS.send([string|int|bool|object], [route string]) // Route lookup will be used.
 */
function websocketCallback(messageObject, pageId) {
    // Interpret and do what you need to with the message:
    const datatype = messageObject.type
    const data = messageObject.data;
    console.log(`Route received ${datatype} data from page ${pageId}: ${data}`)

    // Respond to the page that sent the message if you like:
    Server.message(pageId, 'Route specific messaged received!');
}
Server.addWebsocketCallback('api/search', websocketCallback);

// A bare minimum watcher options object; use for development, omit for production.
const watcherOptions = {
    events: {
        all: watcherCallback, // Just send everything to a single function.
    },
};

// Start the server.
Server.start();

// Watch the current directory for changes; use for development, omit for production.
Server.watch(websiteRoot, watcherOptions);

The options object required by the watch method must include an events property with at least one watched event. The demo code above used all to capture any event. This object takes a lot of settings and is explained below in the Watch Options table.

NSS uses process.cwd() as the live servers root if omitted and is pre-configured with several additional default settings. You can change these by providing your own options object when instantiating the server. How this looks in code is shown below, the following table Server Options explains all available options.

// Make your options object.
const options = {...};

// Get a new instance of NSS and pass in the options.
const Server = new NodeSimpleServer(options);

Note: If you set options.root to a different location than the current directory, you should usually provide the same path or a child path of this path, when you instantiate Server.watch.

:bookmark: Server Options (Object)

contentType    default: text/html

  • The default Content-Type to report to the browser if one can not be determined for a page.

dirListing    default: false

  • If a directory is requested should the directory listing page be shown.

disableAutoRestart    default: false

  • If the server shuts off or crashes do not attempt to auto reconnect to it.

hostAddress    default: 127.0.0.1

  • What IPv4 address or domain name to listen on.

NOTE: This is an advanced setting and should rarely need to be altered.

indexPage    default: index.html

  • If a directory is requested consider this file to be the index page if it exits at that location.

liveReloading    default: true

  • Reload the frontend when changes occur on the backend; disable if using NSS in a production setting.

NOTE: Even if you are not watching for any events this loads a full NSS developer websocket into all pages on the server address. Disabling this will load only a simplified NSS websocket.

port    default: 5000

  • The port number the HTTP and WebSocket server should listen on for requests.

root    default: process.cwd()

  • The absolute path to the directory that should be considered the servers root directory.

:bookmark: Watch Options (Object)

events

  • Set to an object that can have any combination of these properties: all, add, addDir, change, unlink, unlinkDir, ready, raw, error. Any property set on events should point to a callback function that will handle that event.

persistent    default: true

  • Indicates whether the process should continue to run as long as files are being watched.

ignored

  • Defines files/paths to be ignored. The whole relative or absolute path is tested, not just filename. (anymatch-compatible definition)

ignoreInitial    default: false

  • If set to true will not fire add or addDir events when the files/directories are first being discovered.

followSymlinks    default: true

  • When false, only the symlinks themselves will be watched for changes instead of following the link references and bubbling events through the link's path.

cwd

  • The base directory from which watch paths are to be derived. Paths emitted with events will be relative to this path and will use only forward slashes (/) on all operating systems.

disableGlobbing    default: false

  • If set to true then the strings passed to .watch() and .unwatch() are treated as literal path names, even if they look like globs.

usePolling    default: false

  • Whether to use fs.watchFile (backed by polling), or fs.watch. If polling leads to high CPU utilization, consider setting this to false.

interval    default: 100

  • Interval of file system polling, in milliseconds.

binaryInterval    default: 300

  • Interval of file system polling for binary files.

alwaysStat    default: false

  • If relying upon the fs.Stats object that may get passed with add, addDir, and change events, set this to true to ensure it is provided even in cases where it wasn't already available from the underlying watch events.

depth    default: undefined

  • If set, limits how many levels of subdirectories will be traversed when watching for changes.

awaitWriteFinish    default: false

  • By default, the add event will fire when a file first appears on disk, before the entire file has been written.

ignorePermissionErrors    default: false

-Indicates whether to watch files that don't have read permissions if possible. If watching fails due to EPERM or EACCES with this set to true, the errors will be suppressed silently.

atomic    default: true

  • Automatically filters out artifacts that occur when using editors that use "atomic writes" instead of writing directly to the source file.

Most of the Watch Object Options are directly from chokidar which is being used to handle the file monitoring. You may want to visit the chokidar repo for more information. Please note that event paths are altered by NSS to only use forward slashes (/) on all operating systems.

:bookmark: Server Methods

With your new instance of NSS you can call any of the following public methods:

addWebsocketCallback(pattern^, callback)

  • Register a function (callback) to receive messages from the front-end if the pages URL matches the pattern.

getAddresses

  • Returns an array of all the IP addresses you can reach this server at either from the machine itself or on the local area network (LAN).

getWatched

  • Returns an array of watcher objects showing you which directories and files are actively being watched for changes.

message(pageId | pattern^, msg)

  • Send a message (msg) via WebSocket to the page that matches the pageId, or send to a page or pages that match the pattern.

reloadPages()

  • Sends the reload signal to all active pages.

reloadSinglePage(pattern^)

  • Sends the reload signal to a single page or group of pages matching the pattern.

reloadSingleStyles(pattern^)

  • Sends the refreshCSS signal to a single page or group of pages matching the pattern.

reloadStyles()

  • Sends the refreshCSS signal to all active pages.

removeWebsocketCallback(pattern^, callback)

  • Unregister (stop messaging) a callback function that was initially registered with the pattern.

start([callback]) | start([port], [callback])

  • Starts the HTTP and WebSocket servers and notifies callback if present. Port is meant to be an internal option for NSS only but you may specify a port number for NSS to use if you have strict requirements in your environment. NOTE: This is a blocking process and will keep any application that ran it alive until stopped gracefully or forcefully terminated. If you do not want this behavior for any reason you will need to call this in its own process.

stop([callback])

  • Gracefully closes all HTTP and WebSocket connections and turns off the servers, notifying callback if present.

unwatch(paths^^)

  • Stop watching directories or files (paths) for changes previously registered with watch.

watch(paths^^, watchOptionsObject)

  • Start watching a file, files, directory, or directories (paths) for changes and then callback to functions set in watchOptionsObject that will respond to these changes.

watchEnd()

  • Stop watching all registered file, files, directory, or directories for changes.

:bookmark: Symbol Key

^ pattern refers to either a RegExp object or a string of text that represents a regular expression without surrounding slashes (/) or modifiers (g, i, etc.). If you provide a string make sure to correctly escape literal characters. In some instances pattern can also be a string of text representing a page's unique ID. pattern does not recognize glob patterns!

^^ paths refers either to a string or array of strings. Paths to files, directories to be watched recursively, or glob patterns. Globs must not contain windows separators (\), because that's how they work by the standard — you'll need to replace them with forward slashes (/). For additional glob documentation, check out low-level library: picomatch.

Changelog

The current changelog is here. All other changelogs are here.

Contributions

NSS is an open source community supported project, if you would like to help please consider tackling an issue or making a donation to keep the project alive.