IPFS implementation in JavaScript
10K+
AlphaWe've come a long way, but this project is still in Alpha, lots of development is happening, API might change, beware of the Dragons 🐉..
Want to get started? Check our examples folder to learn how to spawn an IPFS node in Node.js and in the Browser.
You can check the development status at the Kanban Board.
This project is available through npm. To install, run:
> npm install ipfs
JS IPFS depends on native modules that are installed by node-gyp. If you have problems running the command above, it is likely that the build tools required by node-gyp are missing from your system. Please install them and then try again.
We support both the Current and Active LTS versions of Node.js. Please see nodejs.org for what these currently are.
This project is tested on macOS, Linux and Windows.
To create an IPFS node programmatically:
const IPFS = require('ipfs')
const node = new IPFS()
node.on('ready', () => {
// Ready to use!
// See https://github.com/ipfs/js-ipfs#core-api
})
In order to use js-ipfs as a CLI, you must install it with the global flag. Run the following (even if you have ipfs installed locally):
npm install ipfs --global
The CLI is available by using the command jsipfs in your terminal. This is aliased, instead of using ipfs, to make sure it does not conflict with the Go implementation.
Learn how to bundle with browserify and webpack in the examples folder.
You can also load it using a <script> using the unpkg CDN or the jsDelivr CDN. Inserting one of the following lines will make a Ipfs object available in the global namespace.
<!-- loading the minified version -->
<script src="https://unpkg.com/ipfs/dist/index.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/ipfs/dist/index.min.js"></script>
<!-- loading the human-readable (not minified) version -->
<script src="https://unpkg.com/ipfs/dist/index.js"></script>
<script src="https://cdn.jsdelivr.net/npm/ipfs/dist/index.js"></script>
Inserting one of the above lines will make an Ipfs object available in the global namespace:
<script>
const node = new window.Ipfs()
node.on('ready', () => {
// Ready to use!
// See https://github.com/ipfs/js-ipfs#core-api
})
</script>
The jsipfs CLI, available when js-ipfs is installed globally, follows(should, it is a WIP) the same interface defined by go-ipfs, you can always use the help command for help menus.
# Install js-ipfs globally
> npm install ipfs --global
> jsipfs --help
Commands:
bitswap A set of commands to manipulate the bitswap agent.
block Manipulate raw IPFS blocks.
bootstrap Show or edit the list of bootstrap peers.
commands List all available commands
config <key> [value] Get and set IPFS config values
daemon Start a long-running daemon process
# ...
js-ipfs uses some different default config values, so that they don't clash directly with a go-ipfs node running in the same machine. These are:
~/.jsipfs (can be changed with env variable IPFS_PATH)40025002The IPFS Daemon exposes the API defined http-api-spec. You can use any of the IPFS HTTP-API client libraries with it, such as: js-ipfs-http-client.
If you want a programmatic way to spawn a IPFS Daemon using JavaScript, check out ipfsd-ctl module
Use the IPFS Module as a dependency of a project to spawn in process instances of IPFS. Create an instance by calling new IPFS() and waiting for its ready event:
// Create the IPFS node instance
const node = new IPFS()
node.on('ready', () => {
// Your node is now ready to use \o/
// stopping a node
node.stop(() => {
// node is now 'offline'
})
})
You can find some examples and tutorials in the examples folder, these exist to help you get started using js-ipfs.
const node = new IPFS([options])
Creates and returns an instance of an IPFS node. Use the options argument to specify advanced configuration. It is an object with any of these properties:
options.repo| Type | Default |
|---|---|
string or ipfs.Repo instance | '~/.jsipfs' in Node.js, 'ipfs' in browsers |
The file path at which to store the IPFS node’s data. Alternatively, you can set up a customized storage system by providing an ipfs.Repo instance.
Example:
// Store data outside your user directory
const node = new IPFS({ repo: '/var/ipfs/data' })
options.init| Type | Default |
|---|---|
| boolean or object | true |
Initialize the repo when creating the IPFS node.
If you have already initialized a repo before creating your IPFS node (e.g. you are loading a repo that was saved to disk from a previous run of your program), you must make sure to set this to false. Note that initializing a repo is different from creating an instance of ipfs.Repo. The IPFS constructor sets many special properties when initializing a repo, so you should usually not try and call repoInstance.init() yourself.
Instead of a boolean, you may provide an object with custom initialization options. All properties are optional:
emptyRepo (boolean) Whether to remove built-in assets, like the instructional tour and empty mutable file system, from the repo. (Default: false)bits (number) Number of bits to use in the generated key pair. (Default: 2048)privateKey (string/PeerId) A pre-generated private key to use. Can be either a base64 string or a PeerId instance. NOTE: This overrides bits.
// Generating a Peer ID:
const PeerId = require('peer-id')
PeerId.create({ bits: 2048 }, (err, peerId) => {
// Generates a new Peer ID, complete with public/private keypair
// See https://github.com/libp2p/js-peer-id
})
pass (string) A passphrase to encrypt keys. You should generally use the top-level pass option instead of the init.pass option (this one will take its value from the top-level option if not set).options.start| Type | Default |
|---|---|
| boolean | true |
If false, do not automatically start the IPFS node. Instead, you’ll need to manually call node.start() yourself.
options.pass| Type | Default |
|---|---|
| string | null |
A passphrase to encrypt/decrypt your keys.
options.silent| Type | Default |
|---|---|
| Boolean | false |
Prevents all logging output from the IPFS node.
options.relay| Type | Default |
|---|---|
| object | { enabled: true, hop: { enabled: false, active: false } } |
Configure circuit relay (see the circuit relay tutorial to learn more).
enabled (boolean): Enable circuit relay dialer and listener. (Default: true)hop (object)
enabled (boolean): Make this node a relay (other nodes can connect through it). (Default: false)active (boolean): Make this an active relay node. Active relay nodes will attempt to dial a destination peer even if that peer is not yet connected to the relay. (Default: false)options.preload| Type | Default |
|---|---|
| object | { enabled: true, addresses: [...] } |
Configure remote preload nodes. The remote will preload content added on this node, and also attempt to preload objects requested by this node.
enabled (boolean): Enable content preloading (Default: true)addresses (array): Multiaddr API addresses of nodes that should preload content. NOTE: nodes specified here should also be added to your node's bootstrap address list at config.Boostrap.options.EXPERIMENTAL| Type | Default |
|---|---|
| object | { pubsub: false, sharding: false, dht: false } |
Enable and configure experimental features.
pubsub (boolean): Enable libp2p pub-sub. (Default: false)ipnsPubsub (boolean): Enable pub-sub on IPNS. (Default: false)sharding (boolean): Enable directory sharding. Directories that have many child objects will be represented by multiple DAG nodes instead of just one. It can improve lookup performance when a directory has several thousand files or more. (Default: false)options.config| Type | Default |
|---|---|
| object | config-nodejs.js in Node.js, config-browser.js in browsers |
Modify the default IPFS node config. This object will be merged with the default config; it will not replace it.
options.libp2p| Type | Default |
|---|---|
| object | libp2p-nodejs.js in Node.js, libp2p-browser.js in browsers |
| function | libp2p bundle |
The libp2p option allows you to build your libp2p node by configuration, or via a bundle function. If you are looking to just modify the below options, using the object format is the quickest way to get the default features of libp2p. If you need to create a more customized libp2p node, such as with custom transports or peer/content routers that need some of the ipfs data on startup, a custom bundle is a great way to achieve this.
You can see the bundle in action in the custom libp2p example.
modules (object):
transport (Array<libp2p.Transport>): An array of Libp2p transport classes/instances to use instead of the defaults. See libp2p/interface-transport for details.peerDiscovery (Array<libp2p.PeerDiscovery>): An array of Libp2p peer discovery classes/instances to use instead of the defaults. See libp2p/peer-discovery for details. If passing a class, configuration can be passed using the config section below under the key corresponding to you module's unique tag (a static property on the class)config (object):
peerDiscovery (object):
[PeerDiscovery.tag] (object): configuration for a peer discovery module
enabled (boolean): whether this module is enabled or disabled[custom config] (any): other keys are specific to the moduledht (object): Configuration options for the DHT
enabled (boolean): whether the DHT is enabled or not (default true in Node.js and false in the browser)kBucketSize (number): bucket size (default 20)randomWalk (object): configuration for random walk
enabled (boolean): whether random DHT walking is enabled (default false)options.connectionManager| Type | Default |
|---|---|
| object | defaults |
Configure the libp2p connection manager.
IPFS instances are Node.js EventEmitters. You can listen for events by calling node.on('event', handler):
const node = new IPFS({ repo: '/var/ipfs/data' })
node.on('error', errorObject => console.error(errorObject))
error is always accompanied by an Error object with information about the error that occurred.
node.on('error', error => {
console.error(error.message)
})
init is emitted after a new repo has been initialized. It will not be emitted if you set the init: false option on the constructor.
ready is emitted when a node is ready to use. This is the final event you will receive when creating a node (after init and start).
When creating a new IPFS node, you should almost always wait for the ready event before calling methods or interacting with the node.
start is emitted when a node has started listening for connections. It will not be emitted if you set the start: false option on the constructor.
stop is emitted when a node has closed all connections and released access to its repo. This is usually the result of calling node.stop().
node.start([callback])Start listening for connections with other IPFS nodes on the network. In most cases, you do not need to call this method — new IPFS() will automatically do it for you.
This method is asynchronous. There are several ways to be notified when the node has finished starting:
If you call node.start() with no arguments, it returns a promise.
const node = new IPFS({ start: false })
node.on('ready', async () => {
console.log('Node is ready to use!')
try {
await node.start()
console.log('Node started!')
} catch (error) {
console.error('Node failed to start!', error)
}
})
If you pass a function as the final argument, it will be called when the node is started (Note: this method will not return a promise if you use a callback function).
const node = new IPFS({ start: false })
node.on('ready', () => {
console.log('Node is ready to use!')
node.start(error => {
if (error) {
return console.error('Node failed to start!', error)
}
console.log('Node started!')
})
})
You can listen for the start event.
const node = new IPFS({ start: false })
node.on('ready', () => {
console.log('Node is ready to use!')
node.start()
})
node.on('error', error => {
console.error('Something went terribly wrong!', error)
})
node.on('start', () => console.log('Node started!'))
node.stop([callback])Close and stop listening for connections with other IPFS nodes, then release access to the node’s repo.
This method is asynchronous. There are several ways to be notified when the node has completely stopped:
If you call node.stop() with no arguments, it returns a promise.
const node = new IPFS()
node.on('ready', async () => {
console.log('Node is ready to use!')
try {
await node.stop()
console.log('Node stopped!')
} catch (error) {
console.error('Node failed to stop cleanly!', error)
}
})
If you pass a function as the final argument, it will be called when the node is stopped (Note: this method will not return a promise if you use a callback function).
const node = new IPFS()
node.on('ready', () => {
console.log('Node is ready to use!')
node.stop(error => {
if (error) {
return console.error('Node failed to stop cleanly!', error)
}
console.log('Node stopped!')
})
})
You can listen for the stop event.
const node = new IPFS()
node.on('ready', () => {
console.log('Node is ready to use!')
node.stop()
})
node.on('error', error => {
console.error('Something went terribly wrong!', error)
})
node.on('stop', () => console.log('Node stopped!'))
The IPFS core API provides all functionality that is not specific to setting up and starting or stopping a node. This API is available directly on an IPFS instance, on the command line (when using the CLI interface), and as an HTTP REST API. For a complete reference, see .
The core API is grouped into several areas:
ipfs.add(data, [options], [callback])ipfs.addPullStream([options])ipfs.addReadableStream([options])ipfs.addFromStream(stream, [callback])ipfs.addFromFs(path, [options], [callback])ipfs.addFromUrl(url, [options], [callback])ipfs.cat(ipfsPath, [options], [callback])ipfs.catPullStream(ipfsPath, [options])ipfs.catReadableStream(ipfsPath, [options])ipfs.get(ipfsPath, [options], [callback])ipfs.getPullStream(ipfsPath, [options])ipfs.getReadableStream(ipfsPath, [options])ipfs.ls(ipfsPath, [callback])ipfs.lsPullStream(ipfsPath)ipfs.lsReadableStream(ipfsPath)ipfs.files.cp([from, to], [callback])ipfs.files.flush([path], [callback])ipfs.files.ls([path], [options], [callback])ipfs.files.mkdir(path, [options], [callback])ipfs.files.mv([from, to], [callback])ipfs.files.read(path, [options], [callback])ipfs.files.readPullStream(path, [options])ipfs.files.readReadableStream(path, [options])ipfs.files.rm(path, [options], [callback])ipfs.files.stat(path, [options], [callback])ipfs.files.write(path, content, [options], [callback])[object (legacy)](https
Content type
Image
Digest
sha256:be9192bbb…
Size
297.3 MB
Last updated
about 3 years ago
Requires Docker Desktop 4.37.1 or later.
Pulls:
104
Last week