Node.js

Node.js

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js is an open-source, cross-platform, JavaScript runtime environment that executes JavaScript code outside a web browser.
fd MOMIN

fd MOMIN

1656744485

How to Run a Flutter Web App with Node.js and API

 

Flutter at a glance

Flutter is one of Google’s solutions to cross-platform development. While it is fairly new on the scene, its feature set makes it an instant competitor in this space.

It compiles your app down to native code that runs on iOS or Android, resulting in incredible end-user performance and frame rates. It supports stateful hot reloading during development, meaning you can make changes to your code and watch them get applied on your emulator or physical device with no need to restart your app or lose your app state.

Flutter’s primary focus has been iOS and Android. With the 1.9 release, web support has been added as a technical preview. It is still in its early days, and it may not be production-ready just yet, but it is certainly exciting and promising. Minimal changes are required to take an existing Flutter app and compile it into an HTML, CSS, and JS bundle, as you will soon see.

Why run a Flutter web app on Node.js?

Flutter web apps can run on any web server. So why would you want to host your Flutter web app on a Node.js server? Well, to be honest, for many of the same reasons that you’d choose Node.js for your other web apps and APIs: it is incredibly good at servicing large volumes of simple requests, you can code your front end and back end in JavaScript, and so on.

You might already have a Node.js API that serves data to your Flutter iOS or Android apps. Compiling your Flutter app as a web app and hosting it on your existing Node.js server might be a logical extension to your current solution, with no need to add additional hosting costs to the equation.

Demonstration

It’s time to dive into the code and see Flutter web in action. In order to follow along with the example, you will need the following tools:

  • Android Studio (Android SDK manager and emulator)
  • Visual Studio Code + Flutter extension (or Android Studio)
  • Node.js 12

Flutter has fantastic developer documentation. If this is your first time developing a Flutter app.

You will have the opportunity to choose which editor you want to develop in. The examples and instructions in this article are based on Visual Studio Code, but you should still be able to follow along if you choose to use Android Studio instead.

A Node.js 12 server is required to run the web version of the Flutter weather app as well as the back-end weather API.

Step 1: Explore the sample code

In order to demonstrate how to add web support to an existing Flutter app, we will start with a simple weather app that has been tested on Android 10 (API level 29).

Flutter Weather App On Mobile

The weather app allows the user to view the current weather for a predefined list of cities. Weather data is retrieved from a back-end server running on Node.js.

Clone the source code for the weather app and server from GitHub:

Tip: The weather-app-nodejs-server repository has a flutter-web-support branch that contains the completed version of the app copied to the server with Flutter web support enabled.

It is best to clone both repositories beside each other in the same parent folder. The contents of the weather_app_flutter repository will be built and copied to a folder within the weather-app-nodejs-server repository.

Explore the Flutter weather app

Open the weather_app_flutter repository in your editor. Let’s take a closer look at the main.dart file. It contains the scaffolding and widgets that make up the app’s user interface. The Home widget class has a fetchWeatherData function that calls the back-end weather API to retrieve data and update the widget’s state:

fetchWeatherData({String location}) async {
    var url = WEATHER_API_URL + location;
    final response = await http.get(url);
    if (response.statusCode == 200) {
      var jsonResponse = convert.jsonDecode(response.body);
      setState(() {
        this._weatherData = WeatherData(
          jsonResponse\['weather'\]['location'],
          jsonResponse\['weather'\]['temperature'],
          jsonResponse\['weather'\]['weatherDescription'],
        );
        this._apiError = null;
      });
    } else {
      setState(() {
        this._apiError =
            'Unable to retrieve weather data from API (HTTP ${response.statusCode})';
      });
    }
  }

The fetchWeatherData function uses Dart’s http package to connect to the server over HTTP. There are other Dart packages that you could use, but this is the officially recommended package if you plan on adding web support to your Flutter app.

Also make note of the WEATHER_API_URL constant. Update the value of this constant before running the app so that it can connect to the API running on your local Node.js server. The URL must contain your machine’s hostname. A localhost URL will not be accessible to the Android emulator or physical device.

Explore the Node.js server and weather API

Open up the weather-app-nodejs-server repository in your editor.

Node.js Server Repository In Our Code Editor

There are a few important files and folders to review:

  • The public/api-test.html file can be used to quickly test that your server is working as expected after startup (e.g., http://localhost:3000/api-test.html)
  • The routes/weather.js file contains a simple GET API that accepts a path parameter and returns weather data (e.g., http://localhost:3000/api/weather/londonon)
  • The public-flutter folder is where you will copy the compiled web version of the weather app. The Node.js server is set up to serve files from this directory to the root context (e.g., http://localhost:3000)

Step 2: Add web support to the Flutter app

Since web support is still a technical preview, you need the latest in-development version of Flutter, also referred to as the master channel. In the root folder of the weather_app_flutter repository, run the following commands:

flutter channel master
flutter upgrade

Tip : You may encounter an “Unknown operating system. Cannot install Dart SDK.” error on Windows when running Flutter commands in a bash shell in Visual Studio Code. Try running the commands in a normal Windows command shell.

The upgrade process may take a few minutes. Next, you will need to enable web support in your Flutter installation so that it is available to this and other apps you develop on this workstation:

flutter config --enable-web
flutter devices

Once web support is enabled, you will see a new Chrome device in the device list. Restart Visual Studio Code after running these commands to refresh the device list menu if you don’t see Chrome in that list yet.

To add web support to the weather app, you need to run this command in the top-level folder of the weather_flutter_app repository:

flutter create .

The create command will make a few modifications to the app, which you can see in this commit. The most notable change is the addition of a web subfolder that contains an index.html:

Index.html File In Our Code Editor

Start the Node.js server by running this command in the root of the weather-app-nodejs-server repository:

npm start

Select Chrome from the device list in Visual Studio Code and then start the debugging. Alternatively, you can run the following flutter command:

flutter run -d chrome

The first time you start the app in Chrome may take a little longer while Flutter downloads additional dependencies on the fly. Chrome will eventually open, and you will see the weather app running in the browser. Some of the styling will be slightly different than what you saw on the emulator or physical device.

App Preview In Chrome

At this point, you will notice that the app is not displaying any data from the weather API. If you open Chrome DevTools, you will see a cross-origin resource sharing error.

The browser is not allowing the request to be made from the Flutter web server to the Node.js server since they are running on different ports. You could solve this problem by enabling cross-origin resource sharing on the server or installing a Chrome plugin to disable CORS.

We are going to ignore the error for now since in the next step we will run the pre-compiled Flutter web code directly on the Node.js server, thus eliminating the cross-origin requests altogether.

Try making a change to some of the code in the main.dart file and let Flutter recompile your app. You will notice that your changes do not immediately appear in the browser. This is because Flutter web does not yet support hot stateful reloading. Hopefully support for this awesome capability will come soon.

Step 3: Run the Flutter web app on Node.js

Now that you can run the weather app in the browser using Flutter, the next step is to build and copy it to the Node.js server to run alongside the API.

To build a Flutter web app bundle, run this command:

flutter build web

The build command will produce the build/web folder containing all the static files that make up the weather app.

Contents Of The build/web Folder In Our Editor

Copy the contents of weather_app_flutter/build/web to weather-app-nodejs-server/public-flutter. If your Node.js server in is still running, stop it and restart it to pick up the new files.

Access your Node.js server in the browser at http://localhost:3000 to see your app running on Node.js. This time, your app will display weather data retrieved from the weather API without the cross-origin resource sharing error.

Final App Running In The Browser

Final thoughts

It is incredible how simple it was to take an existing Flutter app and compile it into a web app ready to be deployed to a web server. The user interface rendered in the browser looks nearly identical to the user interface in Android.

Tread lightly if you are considering Flutter as your cross-platform app framework solely because of its web support. The Flutter team is very clear that web support is missing features, has known performance issues, and is not quite ready for production yet.

Thank for reading!

#node.js #flutter #javascript #wevdev #api

How to Run a Flutter Web App with Node.js and API
Best of Crypto

Best of Crypto

1656650700

How to Subscribe To Binance Websocket Server in Nodejs

Binance Websocket Examples

Local orderbook (Spot)

# Cache local orderbook and echo best price
# btcusdt by default
npm run orderbook

# or provide the trading pair
SYMBOL=bnbusdt npm run orderbook

Spot user data stream

# get user data steam
APIKEY=xxxxxx npm run user

# Get margin account update from websocket
APIKEY=xxxxxx APISECRET=xxxxx npm run margin-user

Futures user data stream

# Get user data steam on production
APIKEY=xxxxxx APISECRET=xxxxx npm run futures-user

# On testnet
APIKEY=xxxxxx APISECRET=xxxxx WSS_BASE_URL="wss://stream.binancefuture.com/" HTTP_BASE_URL="https://testnet.binancefuture.com/" npm run futures-user

Delivery Futures user data stream

# Get user data steam - defaults to production
APIKEY=xxxxxx APISECRET=xxxxx npm run delivery-futures-user

Combined streams

# Get multi pairs stream, setting the pairs in src/multi-stream-depth
npm run multi-stream

Spot trade stream delay monitoring

npm run monitor-spot-trade

Spot depth stream delay monitoring

npm run monitor-spot-depth

Futures depth stream delay monitoring

npm run monitor-futures

How to setup


npm install

# run test
npm run test

Download Details:
Author: binance
Source Code: 
License:

#Binance #blockchain #node #nodejs #websocket

How to Subscribe To Binance Websocket Server in Nodejs
Toby Rogers

Toby Rogers

1656647204

Should Node.js Directly Support Web Workers?

What is the problem this feature will solve?

Creating cross-platform (Node.js + browsers) code has never been more important, but there are still some sharp edges. fetch support was recently added, but there's another important and popular API; Web Workers. Node.js does have worker_threads, but the API differs in many ways and it's really difficult to properly bridge them. There are attempts at bridging these APIs in user-land, but the most popular one is incomplete and not actively maintained.

What is the feature you are proposing to solve the problem?

I propose adding support for Web Workers in Node.js. The Web Workers API is essential to keep apps and servers responsive by moving CPU heavy work off the main thread. I strongly feel it should be part of Node.js.

What alternatives have you considered?

Continue using one of the available polyfills, but that means larger dependency trees, more bugs, and more workaround code

Original article source at https://github.com

#node #nodejs #webworkers

Should Node.js Directly Support Web Workers?
Connor Mills

Connor Mills

1656645860

lru-cache 7.12.0: A Least Recently Used Cache for Node

lru-cache

A cache object that deletes the least-recently-used items.

Specify a max number of the most recently used items that you want to keep, and this cache will keep that many of the most recently accessed items.

This is not primarily a TTL cache, and does not make strong TTL guarantees. There is no preemptive pruning of expired items by default, but you may set a TTL on the cache or on a single set. If you do so, it will treat expired items as missing, and delete them when fetched. If you are more interested in TTL caching than LRU caching, check out @isaacs/ttlcache.

As of version 7, this is one of the most performant LRU implementations available in JavaScript, and supports a wide diversity of use cases. However, note that using some of the features will necessarily impact performance, by causing the cache to have to do more work. See the "Performance" section below.

Installation

npm install lru-cache --save

Usage

const LRU = require('lru-cache')

// At least one of 'max', 'ttl', or 'maxSize' is required, to prevent
// unsafe unbounded storage.
//
// In most cases, it's best to specify a max for performance, so all
// the required memory allocation is done up-front.
//
// All the other options are optional, see the sections below for
// documentation on what each one does.  Most of them can be
// overridden for specific items in get()/set()
const options = {
  max: 500,

  // for use with tracking overall storage size
  maxSize: 5000,
  sizeCalculation: (value, key) => {
    return 1
  },

  // for use when you need to clean up something when objects
  // are evicted from the cache
  dispose: (value, key) => {
    freeFromMemoryOrWhatever(value)
  },

  // how long to live in ms
  ttl: 1000 * 60 * 5,

  // return stale items before removing from cache?
  allowStale: false,

  updateAgeOnGet: false,
  updateAgeOnHas: false,

  // async method to use for cache.fetch(), for
  // stale-while-revalidate type of behavior
  fetchMethod: async (key, staleValue, { options, signal }) => {}
}

const cache = new LRU(options)

cache.set("key", "value")
cache.get("key") // "value"

// non-string keys ARE fully supported
// but note that it must be THE SAME object, not
// just a JSON-equivalent object.
var someObject = { a: 1 }
cache.set(someObject, 'a value')
// Object keys are not toString()-ed
cache.set('[object Object]', 'a different value')
assert.equal(cache.get(someObject), 'a value')
// A similar object with same keys/values won't work,
// because it's a different object identity
assert.equal(cache.get({ a: 1 }), undefined)

cache.clear()    // empty the cache

If you put more stuff in it, then items will fall out.

Options

max

The maximum number (or size) of items that remain in the cache (assuming no TTL pruning or explicit deletions). Note that fewer items may be stored if size calculation is used, and maxSize is exceeded. This must be a positive finite intger.

At least one of max, maxSize, or TTL is required. This must be a positive integer if set.

It is strongly recommended to set a max to prevent unbounded growth of the cache. See "Storage Bounds Safety" below.

maxSize

Set to a positive integer to track the sizes of items added to the cache, and automatically evict items in order to stay below this size. Note that this may result in fewer than max items being stored.

Optional, must be a positive integer if provided. Required if other size tracking features are used.

At least one of max, maxSize, or TTL is required. This must be a positive integer if set.

Even if size tracking is enabled, it is strongly recommended to set a max to prevent unbounded growth of the cache. See "Storage Bounds Safety" below.

sizeCalculation

Function used to calculate the size of stored items. If you're storing strings or buffers, then you probably want to do something like n => n.length. The item is passed as the first argument, and the key is passed as the second argument.

This may be overridden by passing an options object to cache.set().

Requires maxSize to be set.

Deprecated alias: length

fetchMethod

Function that is used to make background asynchronous fetches. Called with fetchMethod(key, staleValue, { signal, options, context }). May return a Promise.

If fetchMethod is not provided, then cache.fetch(key) is equivalent to Promise.resolve(cache.get(key)).

The signal object is an AbortSignal if that's available in the global object, otherwise it's a pretty close polyfill.

If at any time, signal.aborted is set to true, or if the signal.onabort method is called, or if it emits an 'abort' event which you can listen to with addEventListener, then that means that the fetch should be abandoned. This may be passed along to async functions aware of AbortController/AbortSignal behavior.

The options object is a union of the options that may be provided to set() and get(). If they are modified, then that will result in modifying the settings to cache.set() when the value is resolved. For example, a DNS cache may update the TTL based on the value returned from a remote DNS server by changing options.ttl in the fetchMethod.

fetchContext

Arbitrary data that can be passed to the fetchMethod as the context option.

Note that this will only be relevant when the cache.fetch() call needs to call fetchMethod(). Thus, any data which will meaningfully vary the fetch response needs to be present in the key. This is primarily intended for including x-request-id headers and the like for debugging purposes, which do not affect the fetchMethod() response.

noDeleteOnFetchRejection

If a fetchMethod throws an error or returns a rejected promise, then by default, any existing stale value will be removed from the cache.

If noDeleteOnFetchRejection is set to true, then this behavior is suppressed, and the stale value remains in the cache in the case of a rejected fetchMethod.

This is important in cases where a fetchMethod is only called as a background update while the stale value is returned, when allowStale is used.

This may be set in calls to fetch(), or defaulted on the constructor.

dispose

Function that is called on items when they are dropped from the cache, as this.dispose(value, key, reason).

This can be handy if you want to close file descriptors or do other cleanup tasks when items are no longer stored in the cache.

NOTE: It is called before the item has been fully removed from the cache, so if you want to put it right back in, you need to wait until the next tick. If you try to add it back in during the dispose() function call, it will break things in subtle and weird ways.

Unlike several other options, this may not be overridden by passing an option to set(), for performance reasons. If disposal functions may vary between cache entries, then the entire list must be scanned on every cache swap, even if no disposal function is in use.

The reason will be one of the following strings, corresponding to the reason for the item's deletion:

  • evict Item was evicted to make space for a new addition
  • set Item was overwritten by a new value
  • delete Item was removed by explicit cache.delete(key) or by calling cache.clear(), which deletes everything.

The dispose() method is not called for canceled calls to fetchMethod(). If you wish to handle evictions, overwrites, and deletes of in-flight asynchronous fetches, you must use the AbortSignal provided.

Optional, must be a function.

disposeAfter

The same as dispose, but called after the entry is completely removed and the cache is once again in a clean state.

It is safe to add an item right back into the cache at this point. However, note that it is very easy to inadvertently create infinite recursion in this way.

The disposeAfter() method is not called for canceled calls to fetchMethod(). If you wish to handle evictions, overwrites, and deletes of in-flight asynchronous fetches, you must use the AbortSignal provided.

noDisposeOnSet

Set to true to suppress calling the dispose() function if the entry key is still accessible within the cache.

This may be overridden by passing an options object to cache.set().

Boolean, default false. Only relevant if dispose or disposeAfter options are set.

ttl

Max time to live for items before they are considered stale. Note that stale items are NOT preemptively removed by default, and MAY live in the cache, contributing to its LRU max, long after they have expired.

Also, as this cache is optimized for LRU/MRU operations, some of the staleness/TTL checks will reduce performance, as they will incur overhead by deleting from Map objects rather than simply throwing old Map objects away.

This is not primarily a TTL cache, and does not make strong TTL guarantees. There is no pre-emptive pruning of expired items, but you may set a TTL on the cache, and it will treat expired items as missing when they are fetched, and delete them.

Optional, but must be a positive integer in ms if specified.

This may be overridden by passing an options object to cache.set().

At least one of max, maxSize, or TTL is required. This must be a positive integer if set.

Even if ttl tracking is enabled, it is strongly recommended to set a max to prevent unbounded growth of the cache. See "Storage Bounds Safety" below.

If ttl tracking is enabled, and max and maxSize are not set, and ttlAutopurge is not set, then a warning will be emitted cautioning about the potential for unbounded memory consumption.

Deprecated alias: maxAge

noUpdateTTL

Boolean flag to tell the cache to not update the TTL when setting a new value for an existing key (ie, when updating a value rather than inserting a new value). Note that the TTL value is always set (if provided) when adding a new entry into the cache.

This may be passed as an option to cache.set().

Boolean, default false.

ttlResolution

Minimum amount of time in ms in which to check for staleness. Defaults to 1, which means that the current time is checked at most once per millisecond.

Set to 0 to check the current time every time staleness is tested.

Note that setting this to a higher value will improve performance somewhat while using ttl tracking, albeit at the expense of keeping stale items around a bit longer than intended.

ttlAutopurge

Preemptively remove stale items from the cache.

Note that this may significantly degrade performance, especially if the cache is storing a large number of items. It is almost always best to just leave the stale items in the cache, and let them fall out as new items are added.

Note that this means that allowStale is a bit pointless, as stale items will be deleted almost as soon as they expire.

Use with caution!

Boolean, default false

allowStale

By default, if you set ttl, it'll only delete stale items from the cache when you get(key). That is, it's not preemptively pruning items.

If you set allowStale:true, it'll return the stale value as well as deleting it. If you don't set this, then it'll return undefined when you try to get a stale entry.

Note that when a stale entry is fetched, even if it is returned due to allowStale being set, it is removed from the cache immediately. You can immediately put it back in the cache if you wish, thus resetting the TTL.

This may be overridden by passing an options object to cache.get(). The cache.has() method will always return false for stale items.

Boolean, default false, only relevant if ttl is set.

Deprecated alias: stale

noDeleteOnStaleGet

When using time-expiring entries with ttl, by default stale items will be removed from the cache when the key is accessed with cache.get().

Setting noDeleteOnStaleGet to true will cause stale items to remain in the cache, until they are explicitly deleted with cache.delete(key), or retrieved with noDeleteOnStaleGet set to false.

This may be overridden by passing an options object to cache.get().

Boolean, default false, only relevant if ttl is set.

updateAgeOnGet

When using time-expiring entries with ttl, setting this to true will make each item's age reset to 0 whenever it is retrieved from cache with get(), causing it to not expire. (It can still fall out of cache based on recency of use, of course.)

This may be overridden by passing an options object to cache.get().

Boolean, default false, only relevant if ttl is set.

updateAgeOnHas

When using time-expiring entries with ttl, setting this to true will make each item's age reset to 0 whenever its presence in the cache is checked with has(), causing it to not expire. (It can still fall out of cache based on recency of use, of course.)

This may be overridden by passing an options object to cache.has().

Boolean, default false, only relevant if ttl is set.

API

new LRUCache(options)

Create a new LRUCache. All options are documented above, and are on the cache as public members.

cache.max, cache.maxSize, cache.allowStale,

cache.noDisposeOnSet, cache.sizeCalculation, cache.dispose, cache.maxSize, cache.ttl, cache.updateAgeOnGet, cache.updateAgeOnHas

All option names are exposed as public members on the cache object.

These are intended for read access only. Changing them during program operation can cause undefined behavior.

cache.size

The total number of items held in the cache at the current moment.

cache.calculatedSize

The total size of items in cache when using size tracking.

set(key, value, [{ size, sizeCalculation, ttl, noDisposeOnSet, start }])

Add a value to the cache.

Optional options object may contain ttl and sizeCalculation as described above, which default to the settings on the cache object.

If start is provided, then that will set the effective start time for the TTL calculation. Note that this must be a previous value of performance.now() if supported, or a previous value of Date.now() if not.

Options object my also include size, which will prevent calling the sizeCalculation function and just use the specified number if it is a positive integer, and noDisposeOnSet which will prevent calling a dispose function in the case of overwrites.

Will update the recency of the entry.

Returns the cache object.

get(key, { updateAgeOnGet, allowStale } = {}) => value

Return a value from the cache.

Will update the recency of the cache entry found.

If the key is not found, get() will return undefined. This can be confusing when setting values specifically to undefined, as in cache.set(key, undefined). Use cache.has() to determine whether a key is present in the cache at all.

`async fetch(key, { updateAgeOnGet, allowStale, size,

sizeCalculation, ttl, noDisposeOnSet } = {}) => Promise`

If the value is in the cache and not stale, then the returned Promise resolves to the value.

If not in the cache, or beyond its TTL staleness, then fetchMethod(key, staleValue, options) is called, and the value returned will be added to the cache once resolved.

If called with allowStale, and an asynchronous fetch is currently in progress to reload a stale value, then the former stale value will be returned.

Multiple fetches for the same key will only call fetchMethod a single time, and all will be resolved when the value is resolved, even if different options are used.

If fetchMethod is not specified, then this is effectively an alias for Promise.resolve(cache.get(key)).

When the fetch method resolves to a value, if the fetch has not been aborted due to deletion, eviction, or being overwritten, then it is added to the cache using the options provided.

peek(key, { allowStale } = {}) => value

Like get() but doesn't update recency or delete stale items.

Returns undefined if the item is stale, unless allowStale is set either on the cache or in the options object.

has(key, { updateAgeOnHas } = {}) => Boolean

Check if a key is in the cache, without updating the recency of use. Age is updated if updateAgeOnHas is set to true in either the options or the constructor.

Will return false if the item is stale, even though it is technically in the cache.

delete(key)

Deletes a key out of the cache.

Returns true if the key was deleted, false otherwise.

clear()

Clear the cache entirely, throwing away all values.

Deprecated alias: reset()

keys()

Return a generator yielding the keys in the cache, in order from most recently used to least recently used.

rkeys()

Return a generator yielding the keys in the cache, in order from least recently used to most recently used.

values()

Return a generator yielding the values in the cache, in order from most recently used to least recently used.

rvalues()

Return a generator yielding the values in the cache, in order from least recently used to most recently used.

entries()

Return a generator yielding [key, value] pairs, in order from most recently used to least recently used.

rentries()

Return a generator yielding [key, value] pairs, in order from least recently used to most recently used.

find(fn, [getOptions])

Find a value for which the supplied fn method returns a truthy value, similar to Array.find().

fn is called as fn(value, key, cache).

The optional getOptions are applied to the resulting get() of the item found.

dump()

Return an array of [key, entry] objects which can be passed to cache.load()

The start fields are calculated relative to a portable Date.now() timestamp, even if performance.now() is available.

Stale entries are always included in the dump, even if allowStale is false.

Note: this returns an actual array, not a generator, so it can be more easily passed around.

load(entries)

Reset the cache and load in the items in entries in the order listed. Note that the shape of the resulting cache may be different if the same options are not used in both caches.

The start fields are assumed to be calculated relative to a portable Date.now() timestamp, even if performance.now() is available.

purgeStale()

Delete any stale entries. Returns true if anything was removed, false otherwise.

Deprecated alias: prune

getRemainingTTL(key)

Return the number of ms left in the item's TTL. If item is not in cache, returns 0. Returns Infinity if item is in cache without a defined TTL.

forEach(fn, [thisp])

Call the fn function with each set of fn(value, key, cache) in the LRU cache, from most recent to least recently used.

Does not affect recency of use.

If thisp is provided, function will be called in the this-context of the provided object.

rforEach(fn, [thisp])

Same as cache.forEach(fn, thisp), but in order from least recently used to most recently used.

pop()

Evict the least recently used item, returning its value.

Returns undefined if cache is empty.

Internal Methods and Properties

In order to optimize performance as much as possible, "private" members and methods are exposed on the object as normal properties, rather than being accessed via Symbols, private members, or closure variables.

Do not use or rely on these. They will change or be removed without notice. They will cause undefined behavior if used inappropriately. There is no need or reason to ever call them directly.

This documentation is here so that it is especially clear that this not "undocumented" because someone forgot; it is documented, and the documentation is telling you not to do it.

Do not report bugs that stem from using these properties. They will be ignored.

  • initializeTTLTracking() Set up the cache for tracking TTLs
  • updateItemAge(index) Called when an item age is updated, by internal ID
  • setItemTTL(index) Called when an item ttl is updated, by internal ID
  • isStale(index) Called to check an item's staleness, by internal ID
  • initializeSizeTracking() Set up the cache for tracking item size. Called automatically when a size is specified.
  • removeItemSize(index) Updates the internal size calculation when an item is removed or modified, by internal ID
  • addItemSize(index) Updates the internal size calculation when an item is added or modified, by internal ID
  • indexes() An iterator over the non-stale internal IDs, from most recently to least recently used.
  • rindexes() An iterator over the non-stale internal IDs, from least recently to most recently used.
  • newIndex() Create a new internal ID, either reusing a deleted ID, evicting the least recently used ID, or walking to the end of the allotted space.
  • evict() Evict the least recently used internal ID, returning its ID. Does not do any bounds checking.
  • connect(p, n) Connect the p and n internal IDs in the linked list.
  • moveToTail(index) Move the specified internal ID to the most recently used position.
  • keyMap Map of keys to internal IDs
  • keyList List of keys by internal ID
  • valList List of values by internal ID
  • sizes List of calculated sizes by internal ID
  • ttls List of TTL values by internal ID
  • starts List of start time values by internal ID
  • next Array of "next" pointers by internal ID
  • prev Array of "previous" pointers by internal ID
  • head Internal ID of least recently used item
  • tail Internal ID of most recently used item
  • free Stack of deleted internal IDs

Storage Bounds Safety

This implementation aims to be as flexible as possible, within the limits of safe memory consumption and optimal performance.

At initial object creation, storage is allocated for max items. If max is set to zero, then some performance is lost, and item count is unbounded. Either maxSize or ttl must be set if max is not specified.

If maxSize is set, then this creates a safe limit on the maximum storage consumed, but without the performance benefits of pre-allocation. When maxSize is set, every item must provide a size, either via the sizeCalculation method provided to the constructor, or via a size or sizeCalculation option provided to cache.set(). The size of every item must be a positive integer.

If neither max nor maxSize are set, then ttl tracking must be enabled. Note that, even when tracking item ttl, items are not preemptively deleted when they become stale, unless ttlAutopurge is enabled. Instead, they are only purged the next time the key is requested. Thus, if ttlAutopurge, max, and maxSize are all not set, then the cache will potentially grow unbounded.

In this case, a warning is printed to standard error. Future versions may require the use of ttlAutopurge if max and maxSize are not specified.

If you truly wish to use a cache that is bound only by TTL expiration, consider using a Map object, and calling setTimeout to delete entries when they expire. It will perform much better than an LRU cache.

Here is an implementation you may use, under the same license as this package:

// a storage-unbounded ttl cache that is not an lru-cache
const cache = {
  data: new Map(),
  timers: new Map(),
  set: (k, v, ttl) => {
    if (cache.timers.has(k)) {
      clearTimeout(cache.timers.get(k))
    }
    cache.timers.set(k, setTimeout(() => cache.del(k), ttl))
    cache.data.set(k, v)
  },
  get: k => cache.data.get(k),
  has: k => cache.data.has(k),
  delete: k => {
    if (cache.timers.has(k)) {
      clearTimeout(cache.timers.get(k))
    }
    cache.timers.delete(k)
    return cache.data.delete(k)
  },
  clear: () => {
    cache.data.clear()
    for (const v of cache.timers.values()) {
      clearTimeout(v)
    }
    cache.timers.clear()
  }
}

If that isn't to your liking, check out @isaacs/ttlcache.

Performance

As of January 2022, version 7 of this library is one of the most performant LRU cache implementations in JavaScript.

Benchmarks can be extremely difficult to get right. In particular, the performance of set/get/delete operations on objects will vary wildly depending on the type of key used. V8 is highly optimized for objects with keys that are short strings, especially integer numeric strings. Thus any benchmark which tests solely using numbers as keys will tend to find that an object-based approach performs the best.

Note that coercing anything to strings to use as object keys is unsafe, unless you can be 100% certain that no other type of value will be used. For example:

const myCache = {}
const set = (k, v) => myCache[k] = v
const get = (k) => myCache[k]

set({}, 'please hang onto this for me')
set('[object Object]', 'oopsie')

Also beware of "Just So" stories regarding performance. Garbage collection of large (especially: deep) object graphs can be incredibly costly, with several "tipping points" where it increases exponentially. As a result, putting that off until later can make it much worse, and less predictable. If a library performs well, but only in a scenario where the object graph is kept shallow, then that won't help you if you are using large objects as keys.

In general, when attempting to use a library to improve performance (such as a cache like this one), it's best to choose an option that will perform well in the sorts of scenarios where you'll actually use it.

This library is optimized for repeated gets and minimizing eviction time, since that is the expected need of a LRU. Set operations are somewhat slower on average than a few other options, in part because of that optimization. It is assumed that you'll be caching some costly operation, ideally as rarely as possible, so optimizing set over get would be unwise.

If performance matters to you:

  1. If it's at all possible to use small integer values as keys, and you can guarantee that no other types of values will be used as keys, then do that, and use a cache such as lru-fast, or mnemonist's LRUCache which uses an Object as its data store.
  2. Failing that, if at all possible, use short non-numeric strings (ie, less than 256 characters) as your keys, and use mnemonist's LRUCache.
  3. If the types of your keys will be long strings, strings that look like floats, null, objects, or some mix of types, or if you aren't sure, then this library will work well for you.
  4. Do not use a dispose function, size tracking, or especially ttl behavior, unless absolutely needed. These features are convenient, and necessary in some use cases, and every attempt has been made to make the performance impact minimal, but it isn't nothing.

Breaking Changes in Version 7

This library changed to a different algorithm and internal data structure in version 7, yielding significantly better performance, albeit with some subtle changes as a result.

If you were relying on the internals of LRUCache in version 6 or before, it probably will not work in version 7 and above.

For more info, see the change log.

Download Details: 
Author: isaacs
Source Code: https://github.com/isaacs/node-lru-cache 
License: ISC license
#node #javascript #programming

lru-cache 7.12.0: A Least Recently Used Cache for Node
Hermann  Frami

Hermann Frami

1656629280

Serverless Framework Plugin to Export AWS SAM Templates for A Service

Serverless SAM 

Serverless-sam is a plugin for the Serverless framework that makes it easy to create Serverless Application Model (SAM) templates from an application. The plugin adds the sam command to the serverless cli.

Installation

From your Serverless application directory, use npm to install the plugin:

$ npm install --save-dev serverless-sam

Once you have installed the plugin, add it to your serverless.yml file in the plugins sections.

service: my-serverless-service

plugins:
  - serverless-sam

frameworkVersion: ">=1.1.0 <2.0.0"
...

Usage

Use the sam export command to generate a SAM definition from your service. Use the --output or -o option to set the name for the SAM template file.

$ serverless sam export --output ./sam-template.yml

Once you have exported the template, you can follow the standard procedure with the AWS CLI to deploy the service. First, the package command reads the generated templates, uploads the packaged functions to an S3 bucket for deployment, and generates an output template with the S3 links to the function packages.

$ aws cloudformation package \
    --template-file /path_to_template/template.yaml \
    --s3-bucket bucket-name \
    --output-template-file packaged-template.yaml

The next step is to deploy the output template from the package command:

$ aws cloudformation deploy \
    --template-file /path_to_template/packaged-template.yaml \
    --stack-name my-new-stack \
    --capabilities CAPABILITY_IAM

Author: SAPessi
Source Code: https://github.com/SAPessi/serverless-sam 
License: Apache-2.0 license

#serverless #node #plugin #lambda 

Serverless Framework Plugin to Export AWS SAM Templates for A Service
Best of Crypto

Best of Crypto

1656570240

Binance Public API Connector in Nodejs

This is a lightweight library that works as a connector to Binance public API. It’s designed to be simple, clean, and easy to use with minimal dependencies.

  • Supported APIs:
    • /api/*
    • /sapi/*
    • Spot Websocket Market Stream
    • Spot User Data Stream
  • Inclusion of test cases and examples
  • Customizable base URL, request timeout and HTTP proxy
  • Response metadata can be displayed
  • Customizable Logger

Installation

npm install @binance/connector

Documentation

https://binance.github.io/binance-connector-node/

RESTful APIs

const { Spot } = require('@binance/connector')

const apiKey = ''
const apiSecret = ''
const client = new Spot(apiKey, apiSecret)

// Get account information
client.account().then(response => client.logger.log(response.data))

// Place a new order
client.newOrder('BNBUSDT', 'BUY', 'LIMIT', {
  price: '350',
  quantity: 1,
  timeInForce: 'GTC'
}).then(response => client.logger.log(response.data))
  .catch(error => client.logger.error(error))

Please find examples folder to check for more endpoints.

Testnet

While /sapi/* endpoints don't have testnet environment yet, /api/* endpoints can be tested in Spot Testnet. You can use it by changing the base URL:

// provide the testnet base url
const client = new Spot(apiKey, apiSecret, { baseURL: 'https://testnet.binance.vision'})

Base URL

If base_url is not provided, it defaults to api.binance.com.

It's recommended to pass in the base_url parameter, even in production as Binance provides alternative URLs in case of performance issues:

  • https://api1.binance.com
  • https://api2.binance.com
  • https://api3.binance.com

Optional Parameters

Optional parameters are encapsulated to a single object as the last function parameter.

const { Spot } = require('@binance/connector')

const apiKey = ''
const apiSecret = ''
const client = new Spot(apiKey, apiSecret)

client.account({ recvWindow: 2000 }).then(response => client.logger.log(response.data))

Response Metadata

The Binance API server provides weight usages in the headers of each response. This information can be fetched from headers property. x-mbx-used-weight and x-mbx-used-weight-1m show the total weight consumed within 1 minute.

// client initialization is skipped

client.exchangeInfo().then(response => client.logger.log(response.headers['x-mbx-used-weight-1m']))

Custom Logger Integration

const Spot = require('@binance/connector')
const fs = require('fs')
const { Console } = require('console')

// make sure the logs/ folder is created beforehand
const output = fs.createWriteStream('./logs/stdout.log')
const errorOutput = fs.createWriteStream('./logs/stderr.log')

const logger = new Console({ stdout: output, stderr: errorOutput })
const client = new Spot('', '', {logger: logger})

client.exchangeInfo().then(response => client.logger.log(response.data))
// check the output file

The default logger defined in the package is Node.js Console class. Its output is sent to process.stdout and process.stderr, same as the global console.

Error

There are 2 types of error that may be returned from the API server and the user has to handle it properly:

Client error

  • This is thrown when server returns 4XX, it's an issue from client side.
  • The following properties may be helpful to resolve the issue:
    • Response header - Please refer to Response Metadata section for more details.
    • HTTP status code
    • Error code - Server's error code, e.g. -1102
    • Error message - Server's error message, e.g. Unknown order sent.
    • Request config - Configuration send to the server, which can include URL, request method and headers.

Server error

  • This is thrown when server returns 5XX, it's an issue from server side.

Websocket

const { Spot } = require('@binance/connector')

const client = new Spot('', '', {
  wsURL: 'wss://testnet.binance.vision' // If optional base URL is not provided, wsURL defaults to wss://stream.binance.com:9443
})

const callbacks = {
  open: () => client.logger.log('open'),
  close: () => client.logger.log('closed'),
  message: data => client.logger.log(data)
}
const aggTrade = client.aggTradeWS('bnbusdt', callbacks)

// unsubscribe the stream above
setTimeout(() => client.unsubscribe(aggTrade), 3000)

// support combined stream
const combinedStreams = client.combinedStreams(['btcusdt@miniTicker', 'ethusdt@tikcer'], callbacks)

More websocket examples are available in the examples folder

Unsubscribe a Stream

Unsubscription is achieved by closing the connection. If this method is called without any connection established, the console will output a message No connection to close.

// client initialization is skipped
const wsRef = client.aggTradeWS('bnbusdt', callbacks)

// The connection (bnbusdt@aggTrade) is closed after 3 secs.
setTimeout(() => client.unsubscribe(wsRef), 3000)

Auto Reconnect

If there is a close event not initiated by the user, the reconnection mechanism will be triggered in 5 secs.

Custom Logger Integration

const { Console } = require('console')
const fs = require('fs')
const Spot = require('@binance/connector')

const output = fs.createWriteStream('./logs/stdout.log')
const errorOutput = fs.createWriteStream('./logs/stderr.log')

// make sure the logs/ folder is created beforehand
const logger = new Console({ stdout: output, stderr: errorOutput })
const client = new Spot('', '', {logger})

const callbacks = {
  open: () => client.logger.log('open'),
  close: () => client.logger.log('closed'),
  message: data => client.logger.log(data)
}

const wsRef = client.aggTradeWS('bnbusdt', callbacks)
setTimeout(() => client.unsubscribe(wsRef), 5000)
// check the output file

The default logger defined in the package is Node.js Console class. Its output is sent to process.stdout and process.stderr, same as the global console.

Note that when the connection is initialized, the console outputs a list of callbacks in the form of listen to event: <event_name>.

Test

npm install

npm run test

Limitation

Futures and Vanilla Options APIs are not supported:

  • /fapi/*
  • /dapi/*
  • /vapi/*
  • Associated Websocket Market and User Data Streams

Download Details:
Author: binance
Source Code: https://github.com/binance/binance-connector-node
License: MIT license

#Binance #blockchain #node #nodejs #javascript 

Binance Public API Connector in Nodejs
Hoang  Kim

Hoang Kim

1656554574

Cách Sử Sụng fnm - Trình Quản Lý Node Nhanh

Nếu bạn đã làm việc với Node một thời gian, rất có thể bạn sẽ phát hiện ra rằng các dự án của bạn - hoặc dự án bạn đang làm - được viết cho phiên bản Node cũ hơn. Điều đó có nghĩa là chúng sẽ không hoạt động như mong đợi với phiên bản mới nhất.

Trong trường hợp đó, trình quản lý phiên bản Node có thể giúp bạn tiết kiệm thời gian quý báu khi cài đặt và chuyển đổi qua lại giữa các phiên bản Node khác nhau.

Hôm nay tôi sẽ giới thiệu với các bạn fnm(Fast Node Manager), một trình quản lý phiên bản Node, được viết bằng Rust với sự đơn giản và tốc độ. fnmcũng có hỗ trợ nền tảng chéo.

1 Cài đặt cho hệ thống Linux và zsh shell §

Ở đây tôi sẽ chỉ đề cập đến việc cài đặt fnmhệ thống Linux và zshshell. Xem tài liệu hướng dẫn cài đặt cho các nền tảng và trình bao khác.

Trước tiên, hãy đảm bảo rằng curlhệ thống của bạn đã được cài đặt. Sau đó chạy phần sau để cài đặt fnm:

curl -fsSL https://fnm.vercel.app/install | bash -s -- --skip-shell

Nó sẽ cài đặt fnmtrong $HOME/.fnm/thư mục của bạn.

Việc cập nhật fnm cũng giống như cài đặt lại bằng lệnh trên.

1.1 Thiết lập Shell §

Còn một bước quan trọng nữa. Chỉ cần thêm thông tin sau vào .zshrctệp của bạn:

# fnm
export PATH=/home/$USER/.fnm:$PATH
eval "$(fnm env --use-on-cd --version-file-strategy=recursive)"

1.2 Cách cài đặt tập lệnh hoàn thành §

Cài đặt tập lệnh hoàn thành là tùy chọn . Nếu bạn đang thắc mắc về vai trò của bước này, đây là những gì nó làm: nó cố gắng tự động hoàn thành lệnh từng phần mà bạn nhập liên quan đến fnm khi bạn nhấn phím TAB. Ví dụ: nếu bạn nhập fnm ls-và nhấn phím TAB, nó sẽ tự động hoàn thành fnm ls-remote.

fnmđi kèm với tất cả các mã hoàn thành cho các trình bao khác nhau với hệ nhị phân của nó. Bạn sẽ phải dán mã đó vào tệp có tên _fnmtrong thư mục được chỉ định trong FPATHbiến môi trường:

fnm completions --shell zsh > <a_fpath_dir>/_fnm

Xem kết quả đầu ra của echo $FPATHđể lấy tất cả các thư mục có thể có và thay thế <a_fpath_dir>bằng một thư mục thực tế. Bạn nên sử dụng đường dẫn cục bộ của người dùng. Nếu không có đường dẫn nào như vậy, bạn có thể đặt một đường dẫn trong đường dẫn của mình .zshrcbằng cách thêm dòng này:

fpath=(/home/$USER/your/favorite/path/here $fpath)

2 Cách sử dụng phổ biến của fnm §

2.1 Cách liệt kê tất cả các phiên bản Node từ xa §

Để xem tất cả các phiên bản Node khác nhau mà bạn có thể cài đặt, hãy chạy:

fnm ls-remote

Nó sẽ in tất cả các phiên bản như dưới đây:

.
.
.
v16.15.0 (Gallium)
v16.15.1 (Gallium)
v17.0.0
v17.0.1
v17.1.0
v17.2.0
v17.3.0
v17.3.1
v17.4.0
v17.5.0
v17.6.0
v17.7.0
v17.7.1
v17.7.2
v17.8.0
v17.9.0
v17.9.1
v18.0.0
v18.1.0
v18.2.0
v18.3.0

2.2 Cách cài đặt nhiều phiên bản Node §

Hãy cài đặt Node của phiên bản v18.3.0:

fnm install v18.3.0

Để cài đặt Node của phiên bản LTS mới nhất, bạn có thể sử dụng --ltstùy chọn. Vì vậy, hãy chạy phần sau để cài đặt nó:

fnm install --lts

fnmcũng hỗ trợ khớp phiên bản một phần. fnmđoán phiên bản mới nhất hiện có từ đầu vào một phần của bạn. Ví dụ: nếu bạn chỉ làm:

fnm install 17

Nó sẽ cài đặt Node của phiên bản v17.9.1là phiên bản mới nhất có sẵn bắt đầu bằng 17. Vì vậy, hãy thử nghiệm với lệnh trên.

Hãy kiểm tra phiên bản Node của bạn bằng cách nhập vào node --versionthiết bị đầu cuối của bạn. Lưu ý rằng cài đặt đầu tiên được sử dụng theo mặc định.

Trước khi xem cách bắt đầu sử dụng một phiên bản Node đã cài đặt khác, hãy xem cách bạn có thể đặt bí danh (tên) cho một phiên bản để bạn có thể tham khảo dễ dàng.

2.3 Cách đặt bí danh cho phiên bản Node §

Theo mặc định, phiên bản Node đầu tiên mà bạn cài đặt bằng cách sử dụng fnmsẽ nhận được defaultbí danh.

Cú pháp để đặt bí danh cho một phiên bản là:

fnm alias <version> <name>

Nếu bạn muốn đặt bí danh default, có một cách viết tắt:

fnm default <version>

Bạn cũng có thể đặt nhiều bí danh cho một phiên bản.

Cú pháp để xóa bí danh là:

fnm unalias <name>

2.4 Cách sử dụng một phiên bản cụ thể của Node §

Bạn có thể sử dụng Node của một phiên bản cụ thể bằng uselệnh phụ:

fnm use 16

Để kiểm tra phiên bản Node hiện tại, chỉ cần chạy:

fnm current

Để liệt kê tất cả các phiên bản Node mà bạn đã cài đặt fnm, hãy chạy:

fnm ls

fnm-ls-1

Lưu ý rằng bạn có thể bỏ qua fnmvà sử dụng cài đặt Node trên toàn hệ thống trên hệ thống của mình (nếu có) bằng cách sử dụng system:

fnm use system

2.5 Cách đính kèm phiên bản Node vào một dự án §

Bạn có thể tạo một .node-versiontệp trong thư mục gốc của dự án của mình và chỉ cần ghi phiên bản Node mong muốn của dự án đó vào tệp đó như bên dưới để đính kèm phiên bản Node vào nó:

echo 'v18.3.0' > .node-version

fnmtôn trọng tệp này. Vì vậy, nếu bạn đang ở trong thư mục đó, bạn chỉ có thể sử dụng fnm installhoặc fnm usecài đặt hoặc sử dụng phiên bản đó.

fnmcũng tôn trọng .nvmrchồ sơ (nó tương tự như .node-versionhồ sơ nhưng đến từ nvmđất liền). Vì vậy, nếu bạn đã sử dụng nvmtrước đó, bạn sẽ có quá trình chuyển đổi suôn sẻ sang fnm.

fnmcó thể sử dụng các tệp chấm này để phát hiện phiên bản Node và thậm chí bắt đầu sử dụng nó tự động khi sử dụng cd, điều này thực sự tiện dụng trong hầu hết các trường hợp, vì vậy tôi đã bật chúng trong thiết lập shell bằng cách thêm các cờ sau vào fnm envlệnh:

  • --use-on-cd: Cờ này cho biết fnmrằng khi bạn cdvào thư mục gốc của dự án, nó sẽ tự động sử dụng Nút của phiên bản được chỉ định trong .node-version(hoặc .nvmrc). Tuyệt, phải không?
  • --version-file-strategy=recursive: Cờ này và recursivegiá trị của nó về cơ bản cho biết fnmsử dụng phiên bản Node được chỉ định trong .node-version(hoặc .nvmrc) ngay cả khi bạn đang ở trong một thư mục lồng nhau và sử dụng lệnh usehoặc installcon không có phiên bản. Nó cũng yêu fnmcầu sử dụng phiên bản Node có bí danh defaultkhi bạn ra khỏi bất kỳ thư mục dự án nào như vậy và sử dụng uselệnh con không có phiên bản. Sử dụng cờ này cùng với --use-on-cdcho phép bạn có được điều kỳ diệu khi tự động sử dụng hoặc cài đặt Node của phiên bản có liên quan (như được mô tả ở đây) khi bạn đi sâu vào và ra khỏi các thư mục dự án như vậy.

Nếu các tính năng này cản trở quy trình làm việc của bạn, bạn có thể xóa (các) cờ này bất kỳ lúc nào trong thiết lập shell của mình để tắt chúng.

2.6 Cách gỡ cài đặt phiên bản Node §

Gỡ cài đặt một phiên bản của nút rất giống với việc cài đặt nó. Bạn chỉ cần sử dụng lệnh con uninstallthay vì install. Đó là nó.

3 Cách loại bỏ fnm §

Việc xóa fnmcũng đơn giản như xóa thư mục .fnmkhỏi thư mục của bạn homevà xóa cấu hình cụ thể của nó mà bạn đã thêm vào tệp cấu hình shell của mình. Hãy nhớ cũng xóa tập lệnh hoàn thành.

4 Tóm tắt §

Dưới đây là bản tóm tắt của tất cả các lệnh mà chúng tôi đã thảo luận trong bài viết này:

# Listing all remote versions
fnm ls-remote

# Listing all installed ones
fnm ls

# Installing
fnm install <version>

# Uninstalling
fnm uninstall <version>

# Installing node of the latest LTS version
fnm install --lts

# Setting an alias
fnm alias <version> <name>

# Shortcut for setting 'default' as an alias
fnm default <version>

# Removing an alias
fnm unalias <name>

# Using a Node of a particular version
fnm use <version>

# Displaying the version of currently used Node
fnm current

Ngoài ra, nếu bạn cần trợ giúp nhanh, fnmđã có sẵn trợ giúp mà bạn có thể nhận được bất kỳ lúc nào ngay từ thiết bị đầu cuối của mình như bên dưới:

  • Trợ giúp cho fnmlệnh:fnm --help
  • Trợ giúp cho bất kỳ lệnh phụ nàofnm <sub-command> --help

Mã hóa vui vẻ 😄

Nguồn: https://www.freecodecamp.org/news/fnm-fast-node-manager/

#node #fnm 

Cách Sử Sụng fnm - Trình Quản Lý Node Nhanh

Cómo Recuperar Datos De La Base De Datos MySQL Usando AJAX En Node

 MySQL es un sistema de administración de bases de datos relacionales basado en SQL (lenguaje de consulta estructurado), y administrar datos en MySQL no es tan difícil.

En esta guía detallada, descubriremos cómo recuperar datos de la base de datos MySQL usando AJAX en la aplicación Node js. Construiremos un elemento desplegable HTML en el que obtendremos los registros de la base de datos.

Instalaremos algunos paquetes del registro de NPM, y estos paquetes nos ayudarán a conectar Node a la base de datos MySQL y construir las rutas API que interactuarán con la base de datos.

Además, crearemos el script del nodo, que nos ayudará a ejecutar el servidor del nodo.

Averigüemos cómo trabajar con la base de datos MySQL a través de un entorno de nodos.

Cómo obtener datos de la base de datos MySQL usando Node Js y jQuery Ajax

  • Paso 1: crear una aplicación de nodo
  • Paso 2: agregue módulos NPM
  • Paso 3: crear una tabla en la base de datos
  • Paso 4: Conexión a la base de datos
  • Paso 5: Crear archivo de servidor
  • Paso 6: renderizar y mostrar datos en HTML
  • Paso 7: Proyecto de nodo de servicio

Crear aplicación de nodo

Escriba el comando mkdir seguido del nombre de su proyecto y presione enter para crear una nueva carpeta.

mkdir node-vlog

Luego, vaya a la carpeta de la aplicación.

cd node-vlog

Use el comando npm init, este comando crea el archivo package.json , donde permanece la metainformación de su proyecto.

npm init

En la raíz del proyecto, cree un archivo app.js , registre el nombre del archivo en la sección de secuencias de comandos para que esta secuencia de comandos de nodo se pueda invocar mediante la herramienta de línea de comandos.

{
  "main": "app.js",
}

Agregar módulos NPM

Vamos a instalar los siguientes paquetes desde el registro npm, ejecutar el comando e instalar los módulos simultáneamente.

npm install ejs express cors mysql body-parser nodemon

Crear tabla en base de datos

En su base de datos, necesita tener una tabla con algunos registros, para que pueda obtener los datos de la base de datos.

Si no tiene una tabla creada, ejecute el comando sql dado desde la pestaña sql.

CREATE DATABASE nodedb;

CREATE TABLE Country (
  id int not null,
  name varchar(150) not null);
INSERT INTO country VALUES(1,'Colombia');
INSERT INTO country VALUES(2,'Estonia');
INSERT INTO country VALUES(3,'Belgium');
INSERT INTO country VALUES(4,'Austria');
INSERT INTO country VALUES(5,'Denmark');</code></pre>

Conexión de base de datos

En su proyecto de nodo, cree el archivo database.js y luego dentro del código dado, agregue las credenciales de su base de datos para conectar la base de datos a la aplicación de nodo.

var mysql = require('mysql')
var connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'test'
})
connection.connect((err) => {
  if (err) {
    console.log(err)
    return
  }
  console.log('Database connected')
})
module.exports = connection

Crear archivo de servidor

Abra el archivo de script app.js , en este archivo coloque el código dado.

var express = require('express')
var path = require('path')
var createError = require('http-errors')
var cors = require('cors')
var bodyParser = require('body-parser')
var app = express()

var dbMySQLNode = require('./database')
// view engine setup
app.set('views', path.join(__dirname, '/'))
app.set('view engine', 'ejs')
app.use(bodyParser.json())
app.use(
  bodyParser.urlencoded({
    extended: true,
  }),
)

app.use(cors())
app.get('/', (req, res) => {
  res.render('index')
})
app.get('/fetch-countries', function (req, res) {
  dbMySQLNode.query('SELECT * FROM Country ORDER BY id desc', function (
    error,
    response,
  ) {
    if (error) {
      res.json({
        msg: error,
      })
    } else {
      res.json({
        msg: 'Data successfully fetched',
        country: response,
      })
    }
  })
})
app.listen(5555, function () {
  console.log('Node app is being served on port: 5555')
})
module.exports = app

El siguiente script es responsable de configurar el motor de vista ejs, definir la configuración cors, declarar la ruta que se comunicará con la base de datos y definir el puerto de la aplicación.

Renderizar y mostrar datos en HTML

En la raíz de su aplicación, cree el archivo index.ejs , este archivo manejará la vista de su aplicación de nodo. Mostrará los registros que obtiene de la base de datos.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  </head>
  <body>
    <div class="container">
      <h2 class="mb-4">Node js Ajax Get Data from MySQL Example</h2>
      <div class="form-group">
        <label><strong>Countries</strong></label>
        <select class="form-control" id="dynamicDropdown"></select>
      </div>
    </div>
    <script>
      $(document).ready(function () {
        function showCountryCollection() {
          var count_id = this.value;
          $("#dynamicDropdown").html("");
          $.ajax({
            url: "http://localhost:5555/fetch-countries",
            type: "GET",
            dataType: "json",
            success: function (res) {
              console.log(res);
              $("#dynamicDropdown").html('<option value="">Select</option>');
              $.each(res.Country, function (key, value) {
                $("#dynamicDropdown").append(
                  '<option value="' + value.id + '">' + value.name + "</option>"
                );
              });
            },
          });
        }
        showCountryCollection();
      });
    </script>
  </body>
</html>

Proyecto de nodo de servicio

En última instancia, debe evocar el comando sugerido para iniciar la aplicación de nodo.

nodemon

Debe usar esta URL para probar la aplicación:

http://localhost/:5555

 

Conclusión

En esta guía, analizamos el proceso de obtener los resultados de la base de datos MySQL en la aplicación Node js.

Cubrimos cómo obtener los datos de la base de datos MySQL y mostrar los registros en el menú desplegable de selección de HTML en una aplicación Node js usando las dependencias externas.

Esperamos que te haya gustado esta guía y la compartas con otros. 

Fuente: https://www.positronx.io/node-ajax-retrieve-records-from-mysql-database-tutorial/

#mysql #database #node #ajax 

Cómo Recuperar Datos De La Base De Datos MySQL Usando AJAX En Node
Duong Tran

Duong Tran

1656540000

Cách Lấy Dữ Liệu Từ Cơ Sở Dữ Liệu MySQL Bằng AJAX Trong Node

MySQL là một hệ quản trị cơ sở dữ liệu quan hệ dựa trên SQL - Ngôn ngữ truy vấn có cấu trúc và việc quản lý dữ liệu trong MySQL không quá khó.

Trong hướng dẫn chi tiết này, chúng ta sẽ tìm hiểu cách lấy dữ liệu từ cơ sở dữ liệu MySQL bằng AJAX trong ứng dụng Node js. Chúng tôi sẽ xây dựng một phần tử thả xuống HTML trong đó chúng tôi sẽ lấy các bản ghi từ cơ sở dữ liệu.

Chúng tôi sẽ cài đặt một số gói từ sổ đăng ký NPM và các gói này sẽ giúp chúng tôi kết nối Node với cơ sở dữ liệu MySQL và xây dựng các tuyến API sẽ tương tác với cơ sở dữ liệu.

Hơn nữa, chúng tôi sẽ tạo tập lệnh nút, tập lệnh này sẽ giúp chúng tôi chạy máy chủ nút.

Hãy để chúng tôi tìm hiểu cách làm việc với cơ sở dữ liệu MySQL thông qua môi trường nút.

Cách lấy dữ liệu từ cơ sở dữ liệu MySQL bằng Node Js và jQuery Ajax

  • Bước 1: Tạo ứng dụng Node
  • Bước 2: Thêm mô-đun NPM
  • Bước 3: Tạo bảng trong cơ sở dữ liệu
  • Bước 4: Kết nối cơ sở dữ liệu
  • Bước 5: Tạo tệp máy chủ
  • Bước 6: Kết xuất và hiển thị dữ liệu trong HTML
  • Bước 7: Phục vụ dự án nút

Tạo ứng dụng Node

Nhập lệnh mkdir theo sau là tên dự án của bạn và nhấn enter để tạo một thư mục mới.

mkdir node-vlog

Sau đó, chuyển vào thư mục ứng dụng.

cd node-vlog

Sử dụng lệnh npm init, lệnh này tạo tệp package.json , nơi chứa thông tin meta của dự án.

npm init

Trong thư mục gốc của dự án, tạo tệp app.js , đăng ký tên tệp trong phần script để tập lệnh nút này có thể được gọi bằng công cụ dòng lệnh.

{
  "main": "app.js",
}

Thêm mô-đun NPM

Chúng tôi sẽ cài đặt các gói dưới đây từ sổ đăng ký npm, thực thi lệnh và cài đặt các mô-đun đồng thời.

npm install ejs express cors mysql body-parser nodemon

Tạo bảng trong cơ sở dữ liệu

Trong cơ sở dữ liệu của bạn, bạn cần có một bảng với một số bản ghi để bạn có thể lấy dữ liệu từ cơ sở dữ liệu.

Nếu bạn chưa tạo bảng, hãy chạy lệnh sql đã cho từ tab sql.

CREATE DATABASE nodedb;

CREATE TABLE Country (
  id int not null,
  name varchar(150) not null);
INSERT INTO country VALUES(1,'Colombia');
INSERT INTO country VALUES(2,'Estonia');
INSERT INTO country VALUES(3,'Belgium');
INSERT INTO country VALUES(4,'Austria');
INSERT INTO country VALUES(5,'Denmark');</code></pre>

Kết nối cơ sở dữ liệu

Trong dự án nút của bạn, hãy tạo tệp database.js và sau đó bên trong mã đã cho, thêm thông tin đăng nhập cơ sở dữ liệu của bạn để kết nối cơ sở dữ liệu với ứng dụng nút.

var mysql = require('mysql')
var connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'test'
})
connection.connect((err) => {
  if (err) {
    console.log(err)
    return
  }
  console.log('Database connected')
})
module.exports = connection

Tạo tệp máy chủ

Mở tệp script app.js , trong tệp này đặt mã đã cho.

var express = require('express')
var path = require('path')
var createError = require('http-errors')
var cors = require('cors')
var bodyParser = require('body-parser')
var app = express()

var dbMySQLNode = require('./database')
// view engine setup
app.set('views', path.join(__dirname, '/'))
app.set('view engine', 'ejs')
app.use(bodyParser.json())
app.use(
  bodyParser.urlencoded({
    extended: true,
  }),
)

app.use(cors())
app.get('/', (req, res) => {
  res.render('index')
})
app.get('/fetch-countries', function (req, res) {
  dbMySQLNode.query('SELECT * FROM Country ORDER BY id desc', function (
    error,
    response,
  ) {
    if (error) {
      res.json({
        msg: error,
      })
    } else {
      res.json({
        msg: 'Data successfully fetched',
        country: response,
      })
    }
  })
})
app.listen(5555, function () {
  console.log('Node app is being served on port: 5555')
})
module.exports = app

Tập lệnh sau chịu trách nhiệm thiết lập công cụ xem ejs, xác định cài đặt cors, khai báo tuyến sẽ giao tiếp với cơ sở dữ liệu và xác định cổng ứng dụng.

Hiển thị và Hiển thị Dữ liệu trong HTML

Ở gốc ứng dụng của bạn, hãy tạo tệp index.ejs , tệp này sẽ xử lý chế độ xem ứng dụng nút của bạn. Nó sẽ hiển thị các bản ghi mà bạn nhận được từ cơ sở dữ liệu.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  </head>
  <body>
    <div class="container">
      <h2 class="mb-4">Node js Ajax Get Data from MySQL Example</h2>
      <div class="form-group">
        <label><strong>Countries</strong></label>
        <select class="form-control" id="dynamicDropdown"></select>
      </div>
    </div>
    <script>
      $(document).ready(function () {
        function showCountryCollection() {
          var count_id = this.value;
          $("#dynamicDropdown").html("");
          $.ajax({
            url: "http://localhost:5555/fetch-countries",
            type: "GET",
            dataType: "json",
            success: function (res) {
              console.log(res);
              $("#dynamicDropdown").html('<option value="">Select</option>');
              $.each(res.Country, function (key, value) {
                $("#dynamicDropdown").append(
                  '<option value="' + value.id + '">' + value.name + "</option>"
                );
              });
            },
          });
        }
        showCountryCollection();
      });
    </script>
  </body>
</html>

Phục vụ dự án nút

Cuối cùng, bạn cần kích hoạt lệnh được đề xuất để khởi động ứng dụng nút.

nodemon

Bạn yêu cầu sử dụng url này để kiểm tra ứng dụng:

http://localhost/:5555

 

Sự kết luận

Trong hướng dẫn này, chúng tôi đã xem xét quá trình lấy kết quả từ cơ sở dữ liệu MySQL vào ứng dụng Node js.

Chúng tôi đã trình bày cách tìm nạp dữ liệu từ cơ sở dữ liệu MySQL và hiển thị các bản ghi trong trình đơn thả xuống chọn HTML trong ứng dụng Node js bằng cách sử dụng các phụ thuộc bên ngoài.

Chúng tôi hy vọng bạn thích hướng dẫn này và chia sẻ nó với những người khác. 

Nguồn: https://www.positronx.io/node-ajax-retrieve-records-from-mysql-database-tutorial/

#mysql #database #node #ajax 

Cách Lấy Dữ Liệu Từ Cơ Sở Dữ Liệu MySQL Bằng AJAX Trong Node
顾 静

顾 静

1656538800

如何在 Node 中使用 AJAX 从 MySQL 数据库中检索数据

 MySQL 是一个基于 SQL(结构化查询语言)的关系型数据库管理系统,在 MySQL 中管理数据并没有那么困难。

在本详细指南中,我们将了解如何在 Node js 应用程序中使用 AJAX 从 MySQL 数据库中检索数据。我们将构建一个 HTML 下拉元素,我们将从数据库中获取记录。

我们将从 NPM 注册表中安装一些包,这些包将帮助我们将 Node 连接到 MySQL 数据库并构建与数据库交互的 API 路由。

此外,我们将创建节点脚本,这将帮助我们运行节点服务器。

让我们了解如何通过节点环境使用 MySQL 数据库。

如何使用 Node Js 和 jQuery Ajax 从 MySQL 数据库中获取数据

  • 第 1 步:创建节点应用程序
  • 第 2 步:添加 NPM 模块
  • 步骤 3:在数据库中创建表
  • 第 4 步:数据库连接
  • 第 5 步:创建服务器文件
  • 第 6 步:在 HTML 中呈现和显示数据
  • 第 7 步:服务节点项目

创建节点应用

键入 mkdir 命令,后跟您的项目名称,然后按 Enter 创建一个新文件夹。

mkdir node-vlog

然后,进入应用程序文件夹。

cd node-vlog

使用 npm init 命令,该命令会创建package.json文件,您的项目的元信息将保存在该文件中。

npm init

在项目的根目录中创建一个app.js文件,在脚本部分注册文件名,以便可以使用命令行工具调用此节点脚本。

{
  "main": "app.js",
}

添加 NPM 模块

我们将从 npm 注册表安装以下给定的包,执行命令并同时安装模块。

npm install ejs express cors mysql body-parser nodemon

在数据库中创建表

在您的数据库中,您需要有一个包含一些记录的表,以便您可以从数据库中获取数据。

如果您没有创建表,请从 sql 选项卡运行给定的 sql 命令。

CREATE DATABASE nodedb;

CREATE TABLE Country (
  id int not null,
  name varchar(150) not null);
INSERT INTO country VALUES(1,'Colombia');
INSERT INTO country VALUES(2,'Estonia');
INSERT INTO country VALUES(3,'Belgium');
INSERT INTO country VALUES(4,'Austria');
INSERT INTO country VALUES(5,'Denmark');</code></pre>

数据库连接

在您的节点项目中,创建database.js文件,然后在给定的代码中,添加您的数据库凭据,以便将数据库连接到节点应用程序。

var mysql = require('mysql')
var connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'test'
})
connection.connect((err) => {
  if (err) {
    console.log(err)
    return
  }
  console.log('Database connected')
})
module.exports = connection

创建服务器文件

打开app.js脚本文件,在这个文件中放入给定的代码。

var express = require('express')
var path = require('path')
var createError = require('http-errors')
var cors = require('cors')
var bodyParser = require('body-parser')
var app = express()

var dbMySQLNode = require('./database')
// view engine setup
app.set('views', path.join(__dirname, '/'))
app.set('view engine', 'ejs')
app.use(bodyParser.json())
app.use(
  bodyParser.urlencoded({
    extended: true,
  }),
)

app.use(cors())
app.get('/', (req, res) => {
  res.render('index')
})
app.get('/fetch-countries', function (req, res) {
  dbMySQLNode.query('SELECT * FROM Country ORDER BY id desc', function (
    error,
    response,
  ) {
    if (error) {
      res.json({
        msg: error,
      })
    } else {
      res.json({
        msg: 'Data successfully fetched',
        country: response,
      })
    }
  })
})
app.listen(5555, function () {
  console.log('Node app is being served on port: 5555')
})
module.exports = app

以下脚本负责设置 ejs 视图引擎,定义 cors 设置,声明将与数据库通信的路由并定义应用程序端口。

在 HTML 中呈现和显示数据

在您的应用程序的根目录,创建index.ejs文件,该文件将处理您的节点应用程序的视图。它将显示您从数据库中获取的记录。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  </head>
  <body>
    <div class="container">
      <h2 class="mb-4">Node js Ajax Get Data from MySQL Example</h2>
      <div class="form-group">
        <label><strong>Countries</strong></label>
        <select class="form-control" id="dynamicDropdown"></select>
      </div>
    </div>
    <script>
      $(document).ready(function () {
        function showCountryCollection() {
          var count_id = this.value;
          $("#dynamicDropdown").html("");
          $.ajax({
            url: "http://localhost:5555/fetch-countries",
            type: "GET",
            dataType: "json",
            success: function (res) {
              console.log(res);
              $("#dynamicDropdown").html('<option value="">Select</option>');
              $.each(res.Country, function (key, value) {
                $("#dynamicDropdown").append(
                  '<option value="' + value.id + '">' + value.name + "</option>"
                );
              });
            },
          });
        }
        showCountryCollection();
      });
    </script>
  </body>
</html>

服务节点项目

最终,您需要调用建议的命令来启动节点应用程序。

nodemon

您需要使用此 url 来测试应用程序:

http://localhost/:5555

 

结论

在本指南中,我们查看了将结果从 MySQL 数据库获取到 Node js 应用程序的过程。

我们介绍了如何从 MySQL 数据库中获取数据并使用外部依赖项在 Node js 应用程序的 HTML 选择下拉列表中显示记录。

我们希望您喜欢本指南并与他人分享。 

来源:https ://www.positronx.io/node-ajax-retrieve-records-from-mysql-database-tutorial/

#mysql #database #node #ajax 

如何在 Node 中使用 AJAX 从 MySQL 数据库中检索数据
Rui  Silva

Rui Silva

1656537720

Como Recuperar Dados Do Banco De Dados MySQL Usando AJAX No Node

 MySQL é um sistema de gerenciamento de banco de dados relacional baseado em SQL – Structured Query Language, e gerenciar dados no MySQL não é tão difícil.

Neste guia detalhado, descobriremos como recuperar dados do banco de dados MySQL usando AJAX no aplicativo Node js. Construiremos um elemento suspenso HTML no qual obteremos os registros do banco de dados.

Instalaremos alguns pacotes do registro NPM, e esses pacotes nos ajudarão a conectar o Node ao banco de dados MySQL e construir as rotas de API que irão interagir com o banco de dados.

Além disso, criaremos o script do nó, que nos ajudará a executar o servidor do nó.

Vamos descobrir como trabalhar com banco de dados MySQL através de um ambiente de nó.

Como obter dados do banco de dados MySQL usando Node Js e jQuery Ajax

  • Etapa 1: criar aplicativo de nó
  • Etapa 2: adicionar módulos NPM
  • Etapa 3: criar tabela no banco de dados
  • Etapa 4: conexão com o banco de dados
  • Etapa 5: criar arquivo de servidor
  • Etapa 6: renderizar e mostrar dados em HTML
  • Etapa 7: servir o projeto do nó

Criar aplicativo de nó

Digite o comando mkdir seguido pelo nome do seu projeto e pressione Enter para criar uma nova pasta.

mkdir node-vlog

Em seguida, mova para a pasta do aplicativo.

cd node-vlog

Use o comando npm init, este comando cria o arquivo package.json , onde ficam as meta-informações do seu projeto.

npm init

Na raiz do projeto, crie um arquivo app.js , registre o nome do arquivo na seção de scripts para que esse script de nó possa ser invocado usando a ferramenta de linha de comando.

{
  "main": "app.js",
}

Adicionar módulos NPM

Vamos instalar os pacotes abaixo do registro npm, executar o comando e instalar os módulos simultaneamente.

npm install ejs express cors mysql body-parser nodemon

Criar tabela no banco de dados

Em seu banco de dados, você precisa ter uma tabela com alguns registros, para que possa obter os dados do banco de dados.

Se você não tiver a tabela criada, execute o comando sql fornecido na guia sql.

CREATE DATABASE nodedb;

CREATE TABLE Country (
  id int not null,
  name varchar(150) not null);
INSERT INTO country VALUES(1,'Colombia');
INSERT INTO country VALUES(2,'Estonia');
INSERT INTO country VALUES(3,'Belgium');
INSERT INTO country VALUES(4,'Austria');
INSERT INTO country VALUES(5,'Denmark');</code></pre>

Conexão de banco de dados

Em seu projeto de nó, crie o arquivo database.js e, em seguida, dentro do código fornecido, adicione suas credenciais de banco de dados para conectar o banco de dados ao aplicativo de nó.

var mysql = require('mysql')
var connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'test'
})
connection.connect((err) => {
  if (err) {
    console.log(err)
    return
  }
  console.log('Database connected')
})
module.exports = connection

Criar arquivo do servidor

Abra o arquivo de script app.js , neste arquivo coloque o código fornecido.

var express = require('express')
var path = require('path')
var createError = require('http-errors')
var cors = require('cors')
var bodyParser = require('body-parser')
var app = express()

var dbMySQLNode = require('./database')
// view engine setup
app.set('views', path.join(__dirname, '/'))
app.set('view engine', 'ejs')
app.use(bodyParser.json())
app.use(
  bodyParser.urlencoded({
    extended: true,
  }),
)

app.use(cors())
app.get('/', (req, res) => {
  res.render('index')
})
app.get('/fetch-countries', function (req, res) {
  dbMySQLNode.query('SELECT * FROM Country ORDER BY id desc', function (
    error,
    response,
  ) {
    if (error) {
      res.json({
        msg: error,
      })
    } else {
      res.json({
        msg: 'Data successfully fetched',
        country: response,
      })
    }
  })
})
app.listen(5555, function () {
  console.log('Node app is being served on port: 5555')
})
module.exports = app

O script a seguir é responsável por configurar o mecanismo de visualização ejs, definir a configuração do cors, declarar a rota que irá se comunicar com o banco de dados e definir a porta da aplicação.

Renderizar e mostrar dados em HTML

Na raiz da sua aplicação, crie o arquivo index.ejs , este arquivo irá lidar com a visualização da sua aplicação node. Ele exibirá os registros que você obtém do banco de dados.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  </head>
  <body>
    <div class="container">
      <h2 class="mb-4">Node js Ajax Get Data from MySQL Example</h2>
      <div class="form-group">
        <label><strong>Countries</strong></label>
        <select class="form-control" id="dynamicDropdown"></select>
      </div>
    </div>
    <script>
      $(document).ready(function () {
        function showCountryCollection() {
          var count_id = this.value;
          $("#dynamicDropdown").html("");
          $.ajax({
            url: "http://localhost:5555/fetch-countries",
            type: "GET",
            dataType: "json",
            success: function (res) {
              console.log(res);
              $("#dynamicDropdown").html('<option value="">Select</option>');
              $.each(res.Country, function (key, value) {
                $("#dynamicDropdown").append(
                  '<option value="' + value.id + '">' + value.name + "</option>"
                );
              });
            },
          });
        }
        showCountryCollection();
      });
    </script>
  </body>
</html>

Projeto de nó de serviço

Por fim, você precisa evocar o comando sugerido para iniciar o aplicativo do nó.

nodemon

Você precisa usar este URL para testar o aplicativo:

http://localhost/:5555

Conclusão

Neste guia, analisamos o processo de obtenção dos resultados do banco de dados MySQL no aplicativo Node js.

Cobrimos como buscar os dados do banco de dados MySQL e exibir os registros no menu suspenso de seleção de HTML em um aplicativo Node js usando as dependências externas.

Esperamos que você tenha gostado deste guia e o compartilhe com outras pessoas. 

Fonte: https://www.positronx.io/node-ajax-retrieve-records-from-mysql-database-tutorial/

#mysql #database #node #ajax 

Como Recuperar Dados Do Banco De Dados MySQL Usando AJAX No Node
高橋  花子

高橋 花子

1656536400

NodeJSでAJAXを使用してMySQLデータベースからデータを取得する

 MySQLはSQL–構造化クエリ言語に基づくリレーショナルデータベース管理システムであり、MySQLでのデータ管理はそれほど難しくありません。

この詳細なガイドでは、NodejsアプリでAJAXを使用してMySQLデータベースからデータを取得する方法について説明します。データベースからレコードを取得するHTMLドロップダウン要素を作成します。

NPMレジストリからいくつかのパッケージをインストールします。これらのパッケージは、NodeをMySQLデータベースに接続し、データベースと対話するAPIルートを構築するのに役立ちます。

さらに、ノードサーバーの実行に役立つノードスクリプトを作成します。

ノード環境を介してMySQLデータベースを操作する方法を見てみましょう。

NodeJsとjQueryAjaxを使用してMySQLデータベースからデータを取得する方法

  • ステップ1:ノードアプリを作成する
  • ステップ2: NPMモジュールを追加する
  • ステップ3:データベースにテーブルを作成する
  • ステップ4:データベース接続
  • ステップ5:サーバーファイルを作成する
  • ステップ6: HTMLでデータをレンダリングして表示する
  • ステップ7:サーブノードプロジェクト

ノードアプリを作成する

mkdirコマンドに続けてプロジェクト名を入力し、Enterキーを押して新しいフォルダーを作成します。

mkdir node-vlog

次に、アプリケーションフォルダに移動します。

cd node-vlog

npm initコマンドを使用します。このコマンドは、プロジェクトのメタ情報が保持されるpackage.jsonファイルを作成します。

npm init

プロジェクトのルートでapp.jsファイルを作成し、スクリプトセクションにファイル名を登録して、コマンドラインツールを使用してこのノードスクリプトを呼び出せるようにします。

{
  "main": "app.js",
}

NPMモジュールを追加する

npmレジストリから以下のパッケージをインストールし、コマンドを実行して、モジュールを同時にインストールします。

npm install ejs express cors mysql body-parser nodemon

データベースにテーブルを作成する

データベースには、データベースからデータを取得できるように、いくつかのレコードを含むテーブルが必要です。

テーブルを作成していない場合は、[SQL]タブから特定のSQLコマンドを実行します。

CREATE DATABASE nodedb;

CREATE TABLE Country (
  id int not null,
  name varchar(150) not null);
INSERT INTO country VALUES(1,'Colombia');
INSERT INTO country VALUES(2,'Estonia');
INSERT INTO country VALUES(3,'Belgium');
INSERT INTO country VALUES(4,'Austria');
INSERT INTO country VALUES(5,'Denmark');</code></pre>

データベース接続

ノードプロジェクトで、database.jsファイルを作成し、指定されたコード内にデータベースのクレデンシャルを追加して、データベースをノードアプリに接続します。

var mysql = require('mysql')
var connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'test'
})
connection.connect((err) => {
  if (err) {
    console.log(err)
    return
  }
  console.log('Database connected')
})
module.exports = connection

サーバーファイルの作成

app.jsスクリプトファイルを開き、このファイルに指定されたコードを入力します。

var express = require('express')
var path = require('path')
var createError = require('http-errors')
var cors = require('cors')
var bodyParser = require('body-parser')
var app = express()

var dbMySQLNode = require('./database')
// view engine setup
app.set('views', path.join(__dirname, '/'))
app.set('view engine', 'ejs')
app.use(bodyParser.json())
app.use(
  bodyParser.urlencoded({
    extended: true,
  }),
)

app.use(cors())
app.get('/', (req, res) => {
  res.render('index')
})
app.get('/fetch-countries', function (req, res) {
  dbMySQLNode.query('SELECT * FROM Country ORDER BY id desc', function (
    error,
    response,
  ) {
    if (error) {
      res.json({
        msg: error,
      })
    } else {
      res.json({
        msg: 'Data successfully fetched',
        country: response,
      })
    }
  })
})
app.listen(5555, function () {
  console.log('Node app is being served on port: 5555')
})
module.exports = app

次のスクリプトは、ejsビューエンジンのセットアップ、cors設定の定義、データベースと通信するルートの宣言、およびアプリケーションポートの定義を担当します。

HTMLでデータをレンダリングして表示する

アプリケーションのルートで、index.ejsファイルを作成します。このファイルは、ノードアプリのビューを処理します。データベースから取得したレコードが表示されます。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  </head>
  <body>
    <div class="container">
      <h2 class="mb-4">Node js Ajax Get Data from MySQL Example</h2>
      <div class="form-group">
        <label><strong>Countries</strong></label>
        <select class="form-control" id="dynamicDropdown"></select>
      </div>
    </div>
    <script>
      $(document).ready(function () {
        function showCountryCollection() {
          var count_id = this.value;
          $("#dynamicDropdown").html("");
          $.ajax({
            url: "http://localhost:5555/fetch-countries",
            type: "GET",
            dataType: "json",
            success: function (res) {
              console.log(res);
              $("#dynamicDropdown").html('<option value="">Select</option>');
              $.each(res.Country, function (key, value) {
                $("#dynamicDropdown").append(
                  '<option value="' + value.id + '">' + value.name + "</option>"
                );
              });
            },
          });
        }
        showCountryCollection();
      });
    </script>
  </body>
</html>

サーブノードプロジェクト

最終的に、ノードアプリケーションを起動するには、提案されたコマンドを呼び出す必要があります。

nodemon

アプリをテストするには、次のURLを使用する必要があります。

http://localhost/:5555

 

結論

このガイドでは、MySQLデータベースからNodejsアプリに結果を取得するプロセスについて説明しました。

MySQLデータベースからデータをフェッチし、外部依存関係を使用してNodejsアプリのHTML選択ドロップダウンにレコードを表示する方法について説明しました。

このガイドが気に入って、他の人と共有していただければ幸いです。 

ソース:https ://www.positronx.io/node-ajax-retrieve-records-from-mysql-database-tutorial/

#mysql #database #node #ajax 

NodeJSでAJAXを使用してMySQLデータベースからデータを取得する

Récupérer Des Données De La Base De Données MySQL à L'aide D'AJAX

 MySQL est un système de gestion de base de données relationnelle basé sur SQL - Structured Query Language, et la gestion des données dans MySQL n'est pas si difficile.

Dans ce guide détaillé, nous allons découvrir comment récupérer des données de la base de données MySQL en utilisant AJAX dans l'application Node js. Nous allons construire un élément déroulant HTML dans lequel nous obtiendrons les enregistrements de la base de données.

Nous allons installer certains packages à partir du registre NPM, et ces packages nous aideront à connecter Node à la base de données MySQL et à créer les routes API qui interagiront avec la base de données.

De plus, nous allons créer le script de nœud, qui nous aidera à exécuter le serveur de nœud.

Découvrons comment travailler avec la base de données MySQL via un environnement de nœud.

Comment obtenir des données de la base de données MySQL à l'aide de Node Js et jQuery Ajax

  • Étape 1 : Créer une application de nœud
  • Étape 2 : Ajouter des modules NPM
  • Étape 3 : Créer une table dans la base de données
  • Étape 4 : connexion à la base de données
  • Étape 5 : Créer un fichier serveur
  • Étape 6 : Rendre et afficher les données en HTML
  • Étape 7 : Projet de nœud de service

Créer une application de nœud

Tapez la commande mkdir suivie du nom de votre projet et appuyez sur Entrée pour créer un nouveau dossier.

mkdir node-vlog

Ensuite, déplacez-vous dans le dossier de l'application.

cd node-vlog

Utilisez la commande npm init, cette commande crée le fichier package.json , où les méta-informations de votre projet restent.

npm init

À la racine du projet, créez un fichier app.js , enregistrez le nom du fichier dans la section des scripts afin que ce script de nœud puisse être appelé à l'aide de l'outil de ligne de commande.

{
  "main": "app.js",
}

Ajouter des modules NPM

Nous allons installer les packages ci-dessous à partir du registre npm, exécuter la commande et installer les modules simultanément.

npm install ejs express cors mysql body-parser nodemon

Créer une table dans la base de données

Dans votre base de données, vous devez avoir une table avec quelques enregistrements, afin que vous puissiez obtenir les données de la base de données.

Si vous n'avez pas créé de table, exécutez la commande sql donnée à partir de l'onglet sql.

CREATE DATABASE nodedb;

CREATE TABLE Country (
  id int not null,
  name varchar(150) not null);
INSERT INTO country VALUES(1,'Colombia');
INSERT INTO country VALUES(2,'Estonia');
INSERT INTO country VALUES(3,'Belgium');
INSERT INTO country VALUES(4,'Austria');
INSERT INTO country VALUES(5,'Denmark');</code></pre>

Connexion à la base de données

Dans votre projet de nœud, créez le fichier database.js , puis dans le code donné, ajoutez vos informations d'identification de base de données afin de connecter la base de données à l'application de nœud.

var mysql = require('mysql')
var connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'test'
})
connection.connect((err) => {
  if (err) {
    console.log(err)
    return
  }
  console.log('Database connected')
})
module.exports = connection

Créer un fichier serveur

Ouvrez le fichier de script app.js , dans ce fichier mettez le code donné.

var express = require('express')
var path = require('path')
var createError = require('http-errors')
var cors = require('cors')
var bodyParser = require('body-parser')
var app = express()

var dbMySQLNode = require('./database')
// view engine setup
app.set('views', path.join(__dirname, '/'))
app.set('view engine', 'ejs')
app.use(bodyParser.json())
app.use(
  bodyParser.urlencoded({
    extended: true,
  }),
)

app.use(cors())
app.get('/', (req, res) => {
  res.render('index')
})
app.get('/fetch-countries', function (req, res) {
  dbMySQLNode.query('SELECT * FROM Country ORDER BY id desc', function (
    error,
    response,
  ) {
    if (error) {
      res.json({
        msg: error,
      })
    } else {
      res.json({
        msg: 'Data successfully fetched',
        country: response,
      })
    }
  })
})
app.listen(5555, function () {
  console.log('Node app is being served on port: 5555')
})
module.exports = app

Le script suivant est chargé de configurer le moteur de vue ejs, de définir le paramètre cors, de déclarer la route qui communiquera avec la base de données et de définir le port d'application.

Rendu et affichage des données en HTML

A la racine de votre application, créez le fichier index.ejs , ce fichier gérera la vue de votre application node. Il affichera les enregistrements que vous obtenez de la base de données.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  </head>
  <body>
    <div class="container">
      <h2 class="mb-4">Node js Ajax Get Data from MySQL Example</h2>
      <div class="form-group">
        <label><strong>Countries</strong></label>
        <select class="form-control" id="dynamicDropdown"></select>
      </div>
    </div>
    <script>
      $(document).ready(function () {
        function showCountryCollection() {
          var count_id = this.value;
          $("#dynamicDropdown").html("");
          $.ajax({
            url: "http://localhost:5555/fetch-countries",
            type: "GET",
            dataType: "json",
            success: function (res) {
              console.log(res);
              $("#dynamicDropdown").html('<option value="">Select</option>');
              $.each(res.Country, function (key, value) {
                $("#dynamicDropdown").append(
                  '<option value="' + value.id + '">' + value.name + "</option>"
                );
              });
            },
          });
        }
        showCountryCollection();
      });
    </script>
  </body>
</html>

Projet de nœud de service

En fin de compte, vous devez évoquer la commande suggérée pour démarrer l'application de nœud.

nodemon

Vous devez utiliser cette URL pour tester l'application :

http://localhost/:5555

Conclusion

Dans ce guide, nous avons examiné le processus d'obtention des résultats de la base de données MySQL dans l'application Node js.

Nous avons expliqué comment récupérer les données de la base de données MySQL et afficher les enregistrements dans la liste déroulante de sélection HTML dans une application Node js à l'aide des dépendances externes.

Nous espérons que vous avez aimé ce guide et que vous le partagez avec d'autres. 

Source : https://www.positronx.io/node-ajax-retrieve-records-from-mysql-database-tutorial/

#mysql #database #node #ajax 

Récupérer Des Données De La Base De Données MySQL à L'aide D'AJAX

How to Retrieve Data From The MySQL Database using AJAX in Node

 MySQL is a relational database management system based on SQL – Structured Query Language, and managing data in MySQL is not that difficult.

In this detailed guide, we will find out how to retrieve data from the MySQL database using AJAX in the Node js app. We will build an HTML dropdown element in which we will get the records from the database.

We will install some packages from the NPM registry, and these packages will help us connect Node to the MySQL database and build the API routes that will interact with the database.

Furthermore, we will create the node script, which will help us run the node server.

Let us find out how to work with MySQL database through a node environment.

How to Get Data from MySQL Database using Node Js and jQuery Ajax

  • Step 1: Create Node App
  • Step 2: Add NPM Modules
  • Step 3: Create Table in Database
  • Step 4: Database Connection
  • Step 5: Create Server File
  • Step 6: Render and Show Data in HTML
  • Step 7: Serve Node Project

Create Node App

Type the mkdir command followed by your project name and hit enter to create a new folder.

mkdir node-vlog

Then, move into application folder.

cd node-vlog

Use the npm init command, this command creates the package.json file, where your project’s meta information stays.

npm init

In the project’s root create an app.js file, register the file name in scripts section so that this node script can be invoked using the command-line tool.

{
  "main": "app.js",
}

Add NPM Modules

We are going to install the given below packages from the npm registry, execute the command and install the modules simultaneously.

npm install ejs express cors mysql body-parser nodemon

Create Table in Database

In your database, you need to have a table with some records, so that you can get the data from the database.

If you don’t have table created, run the given sql command from the sql tab.

CREATE DATABASE nodedb;

CREATE TABLE Country (
  id int not null,
  name varchar(150) not null);
INSERT INTO country VALUES(1,'Colombia');
INSERT INTO country VALUES(2,'Estonia');
INSERT INTO country VALUES(3,'Belgium');
INSERT INTO country VALUES(4,'Austria');
INSERT INTO country VALUES(5,'Denmark');</code></pre>

Database Connection

In your node project, make the database.js file and then inside the given code, add your database credentials in order to connect the database to the node app.

var mysql = require('mysql')
var connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'test'
})
connection.connect((err) => {
  if (err) {
    console.log(err)
    return
  }
  console.log('Database connected')
})
module.exports = connection

Create Server File

Open the app.js script file, in this file put the given code.

var express = require('express')
var path = require('path')
var createError = require('http-errors')
var cors = require('cors')
var bodyParser = require('body-parser')
var app = express()

var dbMySQLNode = require('./database')
// view engine setup
app.set('views', path.join(__dirname, '/'))
app.set('view engine', 'ejs')
app.use(bodyParser.json())
app.use(
  bodyParser.urlencoded({
    extended: true,
  }),
)

app.use(cors())
app.get('/', (req, res) => {
  res.render('index')
})
app.get('/fetch-countries', function (req, res) {
  dbMySQLNode.query('SELECT * FROM Country ORDER BY id desc', function (
    error,
    response,
  ) {
    if (error) {
      res.json({
        msg: error,
      })
    } else {
      res.json({
        msg: 'Data successfully fetched',
        country: response,
      })
    }
  })
})
app.listen(5555, function () {
  console.log('Node app is being served on port: 5555')
})
module.exports = app

The following script is responsible to set up the ejs view engine, define the cors setting, declare the route that will communicate with database and define the application port.

Render and Show Data in HTML

At the root of your application, make the index.ejs file, this file will handle the view of your node app. It will display the records that you get from the database.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  </head>
  <body>
    <div class="container">
      <h2 class="mb-4">Node js Ajax Get Data from MySQL Example</h2>
      <div class="form-group">
        <label><strong>Countries</strong></label>
        <select class="form-control" id="dynamicDropdown"></select>
      </div>
    </div>
    <script>
      $(document).ready(function () {
        function showCountryCollection() {
          var count_id = this.value;
          $("#dynamicDropdown").html("");
          $.ajax({
            url: "http://localhost:5555/fetch-countries",
            type: "GET",
            dataType: "json",
            success: function (res) {
              console.log(res);
              $("#dynamicDropdown").html('<option value="">Select</option>');
              $.each(res.Country, function (key, value) {
                $("#dynamicDropdown").append(
                  '<option value="' + value.id + '">' + value.name + "</option>"
                );
              });
            },
          });
        }
        showCountryCollection();
      });
    </script>
  </body>
</html>

Serve Node Project

Ultimately, you need to evoke the suggested command to start the node application.

nodemon

You require to use this url to test the app:

http://localhost/:5555

 

Conclusion

In this guide, we looked at the process of getting the results from the MySQL database into the Node js app.

We covered how to fetch the data from the MySQL database and display the records in the HTML select dropdown in a Node js app using the external dependencies.

We hope you liked this guide and share it with others. 

Source: https://www.positronx.io/node-ajax-retrieve-records-from-mysql-database-tutorial/

#mysql #database #node #ajax 

How to Retrieve Data From The MySQL Database using AJAX in Node
Best of Crypto

Best of Crypto

1656478020

Node Binance API: an Asynchronous Node.js Library for The Binance API

Node Binance API

This project is designed to help you make your own projects that interact with the Binance API. You can stream candlestick chart data, market depth, or use other advanced features such as setting stop losses and iceberg orders. This project seeks to have complete API coverage including WebSockets.

Installation: npm install -s node-binance-api

Getting started

const Binance = require('node-binance-api');
const binance = new Binance().options({
  APIKEY: '<key>',
  APISECRET: '<secret>'
});

Binance Futures API

Futures Prices

console.info( await binance.futuresPrices() );

Futures Account Balances & Positions

console.info( await binance.futuresAccount() );

Futures Balances

console.info( await binance.futuresBalance() );

Futures Limit Buy

console.info( await binance.futuresBuy( 'BTCUSDT', 0.1, 8222 ) );

Futures Limit Sell

console.info( await binance.futuresSell( 'BTCUSDT', 0.5, 11111 ) );

Futures Market Buy

console.info( await binance.futuresMarketBuy( 'BNBUSDT', 5 ) );

Futures Market Sell

console.info( await binance.futuresMarketSell( 'TRXUSDT', 1 ) );

Futures Market Orders: Get the fill price using newOrderRespType

console.info( await binance.futuresMarketBuy( 'BNBUSDT', amount, { newOrderRespType: 'RESULT' } ) );

Futures reduceOnly Order Example

if ( side == 'LONG' ) order = await binance.futuresMarketSell( obj.symbol, amount, {reduceOnly: true} )
else order = await binance.futuresMarketBuy( obj.symbol, amount, {reduceOnly: true} )

Get Futures Positions

console.info( await binance.futuresPositionRisk() );

View Example

let position_data = await binance.futuresPositionRisk(), markets = Object.keys( position_data );
for ( let market of markets ) {
  let obj = position_data[market], size = Number( obj.positionAmt );
  if ( size == 0 ) continue;
  console.info( `${leverage}x\t${market}\t${obj.unRealizedProfit}` );
  //console.info( obj ); //positionAmt entryPrice markPrice unRealizedProfit liquidationPrice leverage marginType isolatedMargin isAutoAddMargin maxNotionalValue
}

Adjust Leverage (1-125x)

console.info( await binance.futuresLeverage( 'ETHUSDT', 50 ) );

Adjust Margin Type (ISOLATED, CROSSED)

console.info( await binance.futuresMarginType( 'BTCUSDT', 'ISOLATED' ) );

Adjust Position Margin

// Type: 1: Add postion margin,2: Reduce postion margin
console.info( await binance.futuresPositionMargin( "TRXUSDT", amount, type ) );
console.info( await binance.futuresTime() );
console.info( await binance.futuresExchangeInfo() );
console.info( await binance.futuresCandles( "TRXUSDT", "1m" ) );
console.info( await binance.futuresDepth( "ADAUSDT" ) );
console.info( await binance.futuresQuote() );
console.info( await binance.futuresQuote( "BCHUSDT" ) );
console.info( await binance.futuresDaily() );
console.info( await binance.futuresOpenInterest( "BTCUSDT" ) );
console.info( await binance.futuresMarkPrice() );
console.info( await binance.futuresMarkPrice( "ETHUSDT" ) );
console.info( await binance.futuresTrades( "LTCUSDT" ) );
console.info( await binance.futuresAggTrades( "XTZUSDT" ) );
console.info( await binance.futuresLiquidationOrders() );
console.info( await binance.futuresFundingRate() );
console.info( await binance.futuresHistoricalTrades( "XMRUSDT" ) );
console.info( await binance.futuresLeverageBracket( "LINKUSDT" ) );
console.info( await binance.futuresIncome() );
console.info( await binance.futuresCancelAll( "BTCUSDT" ) );
console.info( await binance.futuresCancel( "BTCUSDT", {orderId: "1025137386"} ) );
console.info( await binance.futuresCountdownCancelAll( "BTCUSDT", 45000 ) );
console.info( await binance.futuresOrderStatus( "BTCUSDT", {orderId: "1025137386"} ) );
console.info( await binance.futuresOpenOrders() );
console.info( await binance.futuresOpenOrders( "BTCUSDT" ) );
console.info( await binance.futuresAllOrders() );
console.info( await binance.futuresAllOrders( "BTCUSDT" ) );
console.info( await binance.futuresUserTrades( "BTCUSDT" ) );
console.info( await binance.futuresGetDataStream() );
console.info( await binance.futuresPositionMarginHistory( "TRXUSDT" ) );
console.info( await binance.promiseRequest( 'v1/time' ) );
// Batch orders, remaining WebSocket streams, and better documentation will be come later

Futures Historical Bulk Data Download API

Get Download ID

console.info( await binance.futuresHistDataId(
  "BTCUSDT", {
    startTime: new Date().getTime() - 24 * 60 * 60 * 1000,
    endTime: new Date().getTime(),
    dataType: 'T_TRADE'
  } )
)

Get Download Link

console.info( await binance.futuresDownloadLink(7343)

Futures WebSocket Streams

Futures miniTicker stream for all symbols

binance.futuresMiniTickerStream( miniTicker => {
    console.info( miniTicker );
} );

Futures miniTicker stream for a symbol

binance.futuresMiniTickerStream( 'BTCUSDT', console.log );

Futures bookTicker stream for all symbols

binance.futuresBookTickerStream( console.log );

Futures bookTicker stream for a symbol

binance.futuresBookTickerStream( 'BTCUSDT', console.log );

Futures prevDay ticker stream for all symbols

binance.futuresTickerStream( console.log );

Futures prevDay ticker stream for a symbol

binance.futuresTickerStream( 'BTCUSDT', console.log );

Futures mark price stream for all symbols

binance.futuresMarkPriceStream( console.log );

Futures mark price stream for a symbol

binance.futuresMarkPriceStream( 'BTCUSDT', console.log );

Futures aggregate trade stream for a symbol

binance.futuresAggTradeStream( 'BTCUSDT', console.log );

Futures complete chart cache

binance.futuresChart( 'BTCUSDT', '1m', console.log );

Futures Liquidation Stream for all symbols

binance.futuresLiquidationStream( console.log );

Futures Liquidation Stream for a symbol

binance.futuresLiquidationStream( 'BTCUSDT', console.log );

Connect to a custom endpoint. Easier shortcut functions will come later

binance.futuresSubscribe( 'btcusdt@kline_4h', console.log );

Terminate an existing socket

binance.futuresTerminate( 'btcusdt@kline_4h' );

Return active sockets and subscriptions

console.log( binance.futuresSubscriptions() );

Delivery API (Futures w/Expiration Date)

deliveryBuy
deliverySell
deliveryMarketBuy
deliveryMarketSell
deliveryPrices
deliveryDaily
deliveryOpenInterest
deliveryExchangeInfo
deliveryOpenOrders
deliveryAllOrders
deliveryCandles
deliveryIndexKlines
deliveryContinuousKlines
deliveryMarkPriceKlines
deliveryMarkPrice
deliveryHistoricalTrades
deliveryTrades
deliveryAggTrades
deliveryUserTrades
deliveryLiquidationOrders
deliveryPositionRisk
deliveryLeverage
deliveryMarginType
deliveryPositionMargin
deliveryPositionMarginHistory
deliveryIncome
deliveryBalance
deliveryAccount
deliveryDepth
deliveryQuote
deliveryLeverageBracket
deliveryOrderStatus
deliveryCancel
deliveryCancelAll
deliveryCountdownCancelAll
deliveryOrder
deliveryGetDataStream
deliveryCloseDataStream
deliveryKeepDataStream
deliveryPing
deliveryTime
deliveryOrder

Binance API (Spot Trading)

Getting latest price of all symbols

let ticker = await binance.prices();
console.info(`Price of BNB: ${ticker.BNBUSDT}`);

Getting latest price of a symbol

binance.prices('BNBBTC', (error, ticker) => {
  console.info("Price of BNB: ", ticker.BNBBTC);
});

View Response

{ ETHBTC: '0.07003500',
  LTCBTC: '0.01176700',
  BNBBTC: '0.00035735',
  NEOBTC: '0.00809500',
  QTUMETH: '0.03851200',
  EOSETH: '0.00189600',
  SNTETH: '0.00008595',
  BNTETH: '0.00738800',
  BCCBTC: '0.08104000',
  GASBTC: '0.00629800',
  BNBETH: '0.00509495',
  BTMETH: '0.00018900',
  HCCBTC: '0.00000180',
  BTCUSDT: '4464.44000000',
  ETHUSDT: '312.89000000',
  HSRBTC: '0.00289000',
  OAXETH: '0.00180000',
  DNTETH: '0.00014190',
  MCOETH: '0.02358300',
  ICNETH: '0.00557000',
  ELCBTC: '0.00000053',
  MCOBTC: '0.00166900',
  WTCBTC: '0.00184138',
  WTCETH: '0.02601700',
  LLTBTC: '0.00001669',
  LRCBTC: '0.00001100',
  LRCETH: '0.00016311',
  QTUMBTC: '0.00271600',
  YOYOBTC: '0.00000481',
  OMGBTC: '0.00187800',
  OMGETH: '0.02677400',
  ZRXBTC: '0.00004319',
  ZRXETH: '0.00060800',
  STRATBTC: '0.00087800',
  STRATETH: '0.01218800',
  SNGLSBTC: '0.00003649',
  SNGLSETH: '0.00051280',
  BQXBTC: '0.00013150',
  BQXETH: '0.00184240',
  KNCBTC: '0.00038969',
  KNCETH: '0.00550320',
  FUNBTC: '0.00000573',
  FUNETH: '0.00008433',
  SNMBTC: '0.00003176',
  SNMETH: '0.00047119',
  NEOETH: '0.11500200',
  IOTABTC: '0.00012136',
  IOTAETH: '0.00171001',
  LINKBTC: '0.00010646',
  LINKETH: '0.00150999',
  XVGBTC: '0.00000145',
  XVGETH: '0.00002059',
  CTRBTC: '0.00025532',
  CTRETH: '0.00375180',
  SALTBTC: '0.00080100',
  SALTETH: '0.01140000',
  MDABTC: '0.00057002',
  MDAETH: '0.00819490' }
//Price of BNB: 0.00035735

Getting list of current balances

binance.balance((error, balances) => {
  if ( error ) return console.error(error);
  console.info("balances()", balances);
  console.info("ETH balance: ", balances.ETH.available);
});
// If you have problems with this function,
// see Troubleshooting at the bottom of this page.

View Response

{ BTC: { available: '0.77206464', onOrder: '0.00177975' },
  LTC: { available: '0.00000000', onOrder: '0.00000000' },
  ETH: { available: '1.14109900', onOrder: '0.00000000' },
  BNC: { available: '0.00000000', onOrder: '0.00000000' },
  ICO: { available: '0.00000000', onOrder: '0.00000000' },
  NEO: { available: '0.00000000', onOrder: '0.00000000' },
  BNB: { available: '41.33761879', onOrder: '0.00000000' },
  QTUM: { available: '0.00000000', onOrder: '0.00000000' },
  EOS: { available: '0.00000000', onOrder: '0.00000000' },
  SNT: { available: '0.00000000', onOrder: '0.00000000' },
  BNT: { available: '0.00000000', onOrder: '0.00000000' },
  GAS: { available: '0.00000000', onOrder: '0.00000000' },
  BCC: { available: '0.00000000', onOrder: '0.00000000' },
  BTM: { available: '0.00000000', onOrder: '0.00000000' },
  USDT: { available: '0.00000000', onOrder: '0.00000000' },
  HCC: { available: '0.00000000', onOrder: '0.00000000' },
  HSR: { available: '0.00000000', onOrder: '0.00000000' },
  OAX: { available: '0.00000000', onOrder: '0.00000000' },
  DNT: { available: '0.00000000', onOrder: '0.00000000' },
  MCO: { available: '0.00000000', onOrder: '0.00000000' },
  ICN: { available: '0.00000000', onOrder: '0.00000000' },
  ELC: { available: '0.00000000', onOrder: '0.00000000' },
  PAY: { available: '0.00000000', onOrder: '0.00000000' },
  ZRX: { available: '0.00000000', onOrder: '0.00000000' },
  OMG: { available: '0.00000000', onOrder: '0.00000000' },
  WTC: { available: '0.00000000', onOrder: '0.00000000' },
  LRX: { available: '0.00000000', onOrder: '0.00000000' },
  YOYO: { available: '0.00000000', onOrder: '0.00000000' },
  LRC: { available: '0.00000000', onOrder: '0.00000000' },
  LLT: { available: '0.00000000', onOrder: '0.00000000' },
  TRX: { available: '0.00000000', onOrder: '0.00000000' },
  FID: { available: '0.00000000', onOrder: '0.00000000' },
  SNGLS: { available: '0.00000000', onOrder: '0.00000000' },
  STRAT: { available: '0.00000000', onOrder: '0.00000000' },
  BQX: { available: '0.00000000', onOrder: '0.00000000' },
  FUN: { available: '0.00000000', onOrder: '0.00000000' },
  KNC: { available: '0.00000000', onOrder: '0.00000000' },
  CDT: { available: '0.00000000', onOrder: '0.00000000' },
  XVG: { available: '0.00000000', onOrder: '0.00000000' },
  IOTA: { available: '0.00000000', onOrder: '0.00000000' },
  SNM: { available: '0.76352833', onOrder: '0.00000000' },
  LINK: { available: '0.00000000', onOrder: '0.00000000' },
  CVC: { available: '0.00000000', onOrder: '0.00000000' },
  TNT: { available: '0.00000000', onOrder: '0.00000000' },
  REP: { available: '0.00000000', onOrder: '0.00000000' },
  CTR: { available: '0.00000000', onOrder: '0.00000000' },
  MDA: { available: '0.00000000', onOrder: '0.00000000' },
  MTL: { available: '0.00000000', onOrder: '0.00000000' },
  SALT: { available: '0.00000000', onOrder: '0.00000000' },
  NULS: { available: '0.00000000', onOrder: '0.00000000' } }
//ETH balance:  1.14109900

Getting bid/ask prices for a symbol

binance.bookTickers('BNBBTC', (error, ticker) => {
  console.info("bookTickers", ticker);
});

View Response

{
  "symbol": "BNBBTC",
  "bidPrice": "4.00000000",
  "bidQty": "431.00000000",
  "askPrice": "4.00000200",
  "askQty": "9.00000000"
}

// from: https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#symbol-order-book-ticker

Getting bid/ask prices for all symbols

binance.bookTickers((error, ticker) => {
  console.info("bookTickers()", ticker);
  console.info("Price of BNB: ", ticker.BNBBTC);
});

View Response

 { ETHBTC:
   { bid: '0.06201000',
     bids: '1.28200000',
     ask: '0.06201300',
     asks: '0.34200000' },
  LTCBTC:
   { bid: '0.01042000',
     bids: '41.45000000',
     ask: '0.01048700',
     asks: '16.81000000' },
  BNBBTC:
   { bid: '0.00028754',
     bids: '727.00000000',
     ask: '0.00028755',
     asks: '400.00000000' },
  NEOBTC:
   { bid: '0.00601800',
     bids: '16.82000000',
     ask: '0.00603700',
     asks: '73.43000000' },
  QTUMETH:
   { bid: '0.04062900',
     bids: '1.30000000',
     ask: '0.04075300',
     asks: '0.58000000' },
  EOSETH:
   { bid: '0.00191400',
     bids: '202.53000000',
     ask: '0.00192500',
     asks: '26.08000000' },
  SNTETH:
   { bid: '0.00007610',
     bids: '403.00000000',
     ask: '0.00007638',
     asks: '19850.00000000' },
  BNTETH:
   { bid: '0.00736800',
     bids: '7.82000000',
     ask: '0.00745900',
     asks: '177.32000000' },
  BCCBTC:
   { bid: '0.06862000',
     bids: '1.56100000',
     ask: '0.06893600',
     asks: '0.81100000' },
  GASBTC:
   { bid: '0.00451700',
     bids: '44.00000000',
     ask: '0.00489700',
     asks: '44.95000000' },
  BNBETH:
   { bid: '0.00462592',
     bids: '32.00000000',
     ask: '0.00467982',
     asks: '57.00000000' },
  BTMETH:
   { bid: '0.00000000',
     bids: '0.00000000',
     ask: '0.00000000',
     asks: '0.00000000' },
  HCCBTC:
   { bid: '0.00000000',
     bids: '0.00000000',
     ask: '0.00000000',
     asks: '0.00000000' },
  BTCUSDT:
   { bid: '4786.01000000',
     bids: '0.58627700',
     ask: '4796.10000000',
     asks: '0.28486400' },
  ETHUSDT:
   { bid: '297.01000000',
     bids: '7.17846000',
     ask: '297.90000000',
     asks: '0.30742000' },
  HSRBTC:
   { bid: '0.00000000',
     bids: '0.00000000',
     ask: '0.00000000',
     asks: '0.00000000' },
  OAXETH:
   { bid: '0.00156200',
     bids: '96.00000000',
     ask: '0.00169900',
     asks: '552.90000000' },
  DNTETH:
   { bid: '0.00011782',
     bids: '1273.00000000',
     ask: '0.00012045',
     asks: '238.00000000' },
  MCOETH:
   { bid: '0.02651200',
     bids: '0.94000000',
     ask: '0.02681200',
     asks: '8.59000000' },
  ICNETH:
   { bid: '0.00484600',
     bids: '448.76000000',
     ask: '0.00490000',
     asks: '0.01000000' },
  ELCBTC:
   { bid: '0.00000000',
     bids: '0.00000000',
     ask: '0.00000000',
     asks: '0.00000000' },
  MCOBTC:
   { bid: '0.00164600',
     bids: '1.00000000',
     ask: '0.00164700',
     asks: '12.11000000' },
  WTCBTC:
   { bid: '0.00132101',
     bids: '124.00000000',
     ask: '0.00133200',
     asks: '98.00000000' },
  WTCETH:
   { bid: '0.02130000',
     bids: '784.35000000',
     ask: '0.02140800',
     asks: '10.70000000' },
  LLTBTC:
   { bid: '0.00000000',
     bids: '0.00000000',
     ask: '0.00000000',
     asks: '0.00000000' },
  LRCBTC:
   { bid: '0.00000000',
     bids: '0.00000000',
     ask: '0.00000000',
     asks: '0.00000000' },
  LRCETH:
   { bid: '0.00000000',
     bids: '0.00000000',
     ask: '0.00000000',
     asks: '0.00000000' },
  QTUMBTC:
   { bid: '0.00252800',
     bids: '123.48000000',
     ask: '0.00253200',
     asks: '10.50000000' },
  YOYOBTC:
   { bid: '0.00000000',
     bids: '0.00000000',
     ask: '0.00000000',
     asks: '0.00000000' },
  OMGBTC:
   { bid: '0.00164900',
     bids: '25.94000000',
     ask: '0.00166400',
     asks: '0.90000000' },
  OMGETH:
   { bid: '0.02660000',
     bids: '9.86000000',
     ask: '0.02698200',
     asks: '43.21000000' },
  ZRXBTC:
   { bid: '0.00003936',
     bids: '117.00000000',
     ask: '0.00003982',
     asks: '8596.00000000' },
  ZRXETH:
   { bid: '0.00062801',
     bids: '239.00000000',
     ask: '0.00063595',
     asks: '2446.00000000' },
  STRATBTC:
   { bid: '0.00070600',
     bids: '43.43000000',
     ask: '0.00070900',
     asks: '15.00000000' },
  STRATETH:
   { bid: '0.01092100',
     bids: '9.00000000',
     ask: '0.01162700',
     asks: '47.90000000' },
  SNGLSBTC:
   { bid: '0.00003162',
     bids: '366.00000000',
     ask: '0.00003183',
     asks: '308.00000000' },
  SNGLSETH:
   { bid: '0.00050064',
     bids: '300.00000000',
     ask: '0.00051543',
     asks: '64.00000000' },
  BQXBTC:
   { bid: '0.00013334',
     bids: '13.00000000',
     ask: '0.00013889',
     asks: '1224.00000000' },
  BQXETH:
   { bid: '0.00200740',
     bids: '990.00000000',
     ask: '0.00228890',
     asks: '80.00000000' },
  KNCBTC:
   { bid: '0.00029509',
     bids: '300.00000000',
     ask: '0.00029842',
     asks: '4.00000000' },
  KNCETH:
   { bid: '0.00481840',
     bids: '411.00000000',
     ask: '0.00484440',
     asks: '10.00000000' },
  FUNBTC:
   { bid: '0.00000461',
     bids: '217.00000000',
     ask: '0.00000465',
     asks: '16668.00000000' },
  FUNETH:
   { bid: '0.00007486',
     bids: '2004.00000000',
     ask: '0.00007617',
     asks: '1419.00000000' },
  SNMBTC:
   { bid: '0.00002462',
     bids: '6922.00000000',
     ask: '0.00002495',
     asks: '404.00000000' },
  SNMETH:
   { bid: '0.00040181',
     bids: '373.00000000',
     ask: '0.00043404',
     asks: '9281.00000000' },
  NEOETH:
   { bid: '0.09610400',
     bids: '8.02000000',
     ask: '0.09891100',
     asks: '5.00000000' },
  IOTABTC:
   { bid: '0.00009674',
     bids: '206.00000000',
     ask: '0.00009721',
     asks: '269.00000000' },
  IOTAETH:
   { bid: '0.00155061',
     bids: '1231.00000000',
     ask: '0.00158100',
     asks: '22.00000000' },
  LINKBTC:
   { bid: '0.00007670',
     bids: '2278.00000000',
     ask: '0.00007697',
     asks: '8000.00000000' },
  LINKETH:
   { bid: '0.00123000',
     bids: '3492.00000000',
     ask: '0.00123999',
     asks: '4000.00000000' },
  XVGBTC:
   { bid: '0.00000111',
     bids: '47758.00000000',
     ask: '0.00000113',
     asks: '215443.00000000' },
  XVGETH:
   { bid: '0.00001801',
     bids: '8329.00000000',
     ask: '0.00001842',
     asks: '85146.00000000' },
  CTRBTC:
   { bid: '0.00019801',
     bids: '650.00000000',
     ask: '0.00021103',
     asks: '49.00000000' },
  CTRETH:
   { bid: '0.00320200',
     bids: '538.00000000',
     ask: '0.00351990',
     asks: '2081.00000000' },
  SALTBTC:
   { bid: '0.00063900',
     bids: '57.13000000',
     ask: '0.00064000',
     asks: '96.48000000' },
  SALTETH:
   { bid: '0.01030200',
     bids: '728.27000000',
     ask: '0.01038900',
     asks: '0.04000000' },
  MDABTC:
   { bid: '0.00039031',
     bids: '282.00000000',
     ask: '0.00039994',
     asks: '540.00000000' },
  MDAETH:
   { bid: '0.00635500',
     bids: '432.00000000',
     ask: '0.00641990',
     asks: '185.00000000' },
  MTLBTC:
   { bid: '0.00145500',
     bids: '45.00000000',
     ask: '0.00145600',
     asks: '42.12000000' },
  MTLETH:
   { bid: '0.02300100',
     bids: '96.10000000',
     ask: '0.02477400',
     asks: '131.90000000' },
  SUBBTC:
   { bid: '0.00003250',
     bids: '4474.00000000',
     ask: '0.00003380',
     asks: '3878.00000000' },
  SUBETH:
   { bid: '0.00053000',
     bids: '740.00000000',
     ask: '0.00053501',
     asks: '580.00000000' } }
/* Price of BNB:  { bid: '0.00028754',
  bids: '727.00000000',
  ask: '0.00028755',
  asks: '400.00000000' } */

Get all bid/ask prices

binance.bookTickers((error, ticker) => {
  console.info("bookTickers", ticker);
});

View Response

{ ETHBTC:
   { bid: '0.06187700',
     bids: '0.64000000',
     ask: '0.06188300',
     asks: '6.79700000' },
  LTCBTC:
   { bid: '0.01036000',
     bids: '14.96000000',
     ask: '0.01037000',
     asks: '0.60000000' },
  BNBBTC:
   { bid: '0.00028226',
     bids: '802.00000000',
     ask: '0.00028268',
     asks: '584.00000000' },
  NEOBTC:
   { bid: '0.00595600',
     bids: '33.00000000',
     ask: '0.00595900',
     asks: '37.00000000' },
  QTUMETH:
   { bid: '0.03958000',
     bids: '1.42000000',
     ask: '0.04024300',
     asks: '7.46000000' },
  EOSETH:
   { bid: '0.00192600',
     bids: '29.31000000',
     ask: '0.00193500',
     asks: '418.91000000' },
  SNTETH:
   { bid: '0.00007607',
     bids: '8864.00000000',
     ask: '0.00007682',
     asks: '1311.00000000' },
  BNTETH:
   { bid: '0.00740200',
     bids: '1.36000000',
     ask: '0.00746800',
     asks: '419.86000000' },
  BCCBTC:
   { bid: '0.06786500',
     bids: '0.18600000',
     ask: '0.06835400',
     asks: '0.72600000' },
  GASBTC:
   { bid: '0.00435500',
     bids: '332.73000000',
     ask: '0.00435600',
     asks: '18.31000000' },
  BNBETH:
   { bid: '0.00456443',
     bids: '4.00000000',
     ask: '0.00461795',
     asks: '192.00000000' },
  BTMETH:
   { bid: '0.00000000',
     bids: '0.00000000',
     ask: '0.00000000',
     asks: '0.00000000' },
  HCCBTC:
   { bid: '0.00000000',
     bids: '0.00000000',
     ask: '0.00000000',
     asks: '0.00000000' },
  BTCUSDT:
   { bid: '4801.05000000',
     bids: '0.82289400',
     ask: '4812.00000000',
     asks: '1.04753200' },
  ETHUSDT:
   { bid: '296.32000000',
     bids: '3.24294000',
     ask: '297.81000000',
     asks: '17.69901000' },
  HSRBTC:
   { bid: '0.00000000',
     bids: '0.00000000',
     ask: '0.00000000',
     asks: '0.00000000' },
  OAXETH:
   { bid: '0.00154500',
     bids: '422.64000000',
     ask: '0.00169200',
     asks: '159.94000000' },
  DNTETH:
   { bid: '0.00012059',
     bids: '434.00000000',
     ask: '0.00012100',
     asks: '8311.00000000' },
  MCOETH:
   { bid: '0.02566000',
     bids: '5.85000000',
     ask: '0.02651200',
     asks: '4.37000000' },
  ICNETH:
   { bid: '0.00489000',
     bids: '232.97000000',
     ask: '0.00500000',
     asks: '0.01000000' },
  ELCBTC:
   { bid: '0.00000000',
     bids: '0.00000000',
     ask: '0.00000000',
     asks: '0.00000000' },
  MCOBTC:
   { bid: '0.00162700',
     bids: '2.87000000',
     ask: '0.00163800',
     asks: '0.70000000' },
  WTCBTC:
   { bid: '0.00129604',
     bids: '600.00000000',
     ask: '0.00131600',
     asks: '1.00000000' },
  WTCETH:
   { bid: '0.02080000',
     bids: '30.00000000',
     ask: '0.02097600',
     asks: '24.00000000' },
  LLTBTC:
   { bid: '0.00000000',
     bids: '0.00000000',
     ask: '0.00000000',
     asks: '0.00000000' },
  LRCBTC:
   { bid: '0.00000000',
     bids: '0.00000000',
     ask: '0.00000000',
     asks: '0.00000000' },
  LRCETH:
   { bid: '0.00000000',
     bids: '0.00000000',
     ask: '0.00000000',
     asks: '0.00000000' },
  QTUMBTC:
   { bid: '0.00245100',
     bids: '43.11000000',
     ask: '0.00248500',
     asks: '74.96000000' },
  YOYOBTC:
   { bid: '0.00000000',
     bids: '0.00000000',
     ask: '0.00000000',
     asks: '0.00000000' },
  OMGBTC:
   { bid: '0.00160700',
     bids: '300.00000000',
     ask: '0.00161300',
     asks: '36.05000000' },
  OMGETH:
   { bid: '0.02597100',
     bids: '4.92000000',
     ask: '0.02633200',
     asks: '19.00000000' },
  ZRXBTC:
   { bid: '0.00003852',
     bids: '9.00000000',
     ask: '0.00003912',
     asks: '103.00000000' },
  ZRXETH:
   { bid: '0.00062997',
     bids: '645.00000000',
     ask: '0.00062998',
     asks: '5376.00000000' },
  STRATBTC:
   { bid: '0.00069200',
     bids: '50.50000000',
     ask: '0.00070000',
     asks: '6.54000000' },
  STRATETH:
   { bid: '0.01080400',
     bids: '5.00000000',
     ask: '0.01200000',
     asks: '5.88000000' },
  SNGLSBTC:
   { bid: '0.00003121',
     bids: '726.00000000',
     ask: '0.00003161',
     asks: '153.00000000' },
  SNGLSETH:
   { bid: '0.00046686',
     bids: '4782.00000000',
     ask: '0.00051906',
     asks: '32.00000000' },
  BQXBTC:
   { bid: '0.00011512',
     bids: '87.00000000',
     ask: '0.00011840',
     asks: '133.00000000' },
  BQXETH:
   { bid: '0.00183080',
     bids: '1051.00000000',
     ask: '0.00195000',
     asks: '626.00000000' },
  KNCBTC:
   { bid: '0.00027859',
     bids: '7.00000000',
     ask: '0.00028462',
     asks: '35.00000000' },
  KNCETH:
   { bid: '0.00452830',
     bids: '13.00000000',
     ask: '0.00454970',
     asks: '35.00000000' },
  FUNBTC:
   { bid: '0.00000464',
     bids: '753.00000000',
     ask: '0.00000465',
     asks: '13924.00000000' },
  FUNETH:
   { bid: '0.00007126',
     bids: '44131.00000000',
     ask: '0.00007617',
     asks: '1419.00000000' },
  SNMBTC:
   { bid: '0.00002489',
     bids: '564.00000000',
     ask: '0.00002559',
     asks: '2553.00000000' },
  SNMETH:
   { bid: '0.00040060',
     bids: '374.00000000',
     ask: '0.00041494',
     asks: '7624.00000000' },
  NEOETH:
   { bid: '0.09604700',
     bids: '22.05000000',
     ask: '0.09800000',
     asks: '0.31000000' },
  IOTABTC:
   { bid: '0.00009515',
     bids: '3.00000000',
     ask: '0.00009529',
     asks: '147.00000000' },
  IOTAETH:
   { bid: '0.00150002',
     bids: '4311.00000000',
     ask: '0.00155216',
     asks: '7.00000000' },
  LINKBTC:
   { bid: '0.00007601',
     bids: '4337.00000000',
     ask: '0.00007630',
     asks: '525.00000000' },
  LINKETH:
   { bid: '0.00121903',
     bids: '3784.00000000',
     ask: '0.00122965',
     asks: '200.00000000' },
  XVGBTC:
   { bid: '0.00000113',
     bids: '470101.00000000',
     ask: '0.00000114',
     asks: '147728.00000000' },
  XVGETH:
   { bid: '0.00001813',
     bids: '8274.00000000',
     ask: '0.00001843',
     asks: '8320.00000000' },
  CTRBTC:
   { bid: '0.00020202',
     bids: '625.00000000',
     ask: '0.00020649',
     asks: '1143.00000000' },
  CTRETH:
   { bid: '0.00330510',
     bids: '387.00000000',
     ask: '0.00339330',
     asks: '436.00000000' },
  SALTBTC:
   { bid: '0.00063500',
     bids: '76.00000000',
     ask: '0.00064300',
     asks: '437.54000000' },
  SALTETH:
   { bid: '0.01014200',
     bids: '202.79000000',
     ask: '0.01122600',
     asks: '1.36000000' },
  MDABTC:
   { bid: '0.00038061',
     bids: '8.00000000',
     ask: '0.00041300',
     asks: '1772.00000000' },
  MDAETH:
   { bid: '0.00655000',
     bids: '547.00000000',
     ask: '0.00660830',
     asks: '8814.00000000' },
  MTLBTC:
   { bid: '0.00140600',
     bids: '0.11000000',
     ask: '0.00143800',
     asks: '12.00000000' },
  MTLETH:
   { bid: '0.02300000',
     bids: '1166.86000000',
     ask: '0.02489500',
     asks: '13.98000000' },
  SUBBTC:
   { bid: '0.00003580',
     bids: '7617.00000000',
     ask: '0.00003619',
     asks: '1052.00000000' },
  SUBETH:
   { bid: '0.00056500',
     bids: '3649.00000000',
     ask: '0.00059988',
     asks: '3649.00000000' } }

Get market depth for a symbol

binance.depth("BNBBTC", (error, depth, symbol) => {
  console.info(symbol+" market depth", depth);
});

View Response

market depth for BNBBTC
{ bids:
   { '0.00022997': '49.00000000',
     '0.00022867': '11.00000000',
     '0.00022865': '1149.00000000',
     '0.00022810': '20.00000000',
     '0.00022800': '1000.00000000',
     '0.00022777': '1350.00000000',
     '0.00022774': '96.00000000',
     '0.00022765': '5.00000000',
     '0.00022741': '12.00000000',
     '0.00022705': '1372.00000000',
     '0.00022700': '402.00000000',
     '0.00022514': '756.00000000',
     '0.00022513': '761.00000000',
     '0.00022502': '2244.00000000',
     '0.00022501': '2190.00000000',
     '0.00022500': '5069.00000000',
     '0.00022419': '1871.00000000',
     '0.00022418': '1667.00000000',
     '0.00022167': '1889.00000000',
     '0.00022162': '1014.00000000',
     '0.00022112': '13563.00000000',
     '0.00022078': '4056.00000000',
     '0.00022000': '8060.00000000',
     '0.00021963': '13563.00000000',
     '0.00021850': '52.00000000',
     '0.00021800': '1282.00000000',
     '0.00021710': '102.00000000',
     '0.00021680': '100.00000000',
     '0.00021652': '29.00000000',
     '0.00021641': '154.00000000',
     '0.00021500': '1491.00000000',
     '0.00021471': '977.00000000',
     '0.00021405': '478.00000000',
     '0.00021400': '11.00000000',
     '0.00021314': '686.00000000',
     '0.00021219': '1089.00000000',
     '0.00021200': '767.00000000',
     '0.00021100': '5000.00000000',
     '0.00021011': '50.00000000',
     '0.00021000': '3468.00000000',
     '0.00020900': '169.00000000',
     '0.00020843': '90.00000000',
     '0.00020811': '200.00000000',
     '0.00020702': '50.00000000',
     '0.00020691': '283.00000000',
     '0.00020600': '3703.00000000',
     '0.00020500': '107.00000000',
     '0.00020450': '6363.00000000',
     '0.00020250': '301.00000000',
     '0.00020222': '200.00000000',
     '0.00020200': '123.00000000',
     '0.00020137': '50.00000000',
     '0.00020122': '727.00000000',
     '0.00020100': '6400.00000000',
     '0.00020088': '10.00000000',
     '0.00020020': '793.00000000',
     '0.00020010': '500.00000000',
     '0.00020009': '44.00000000',
     '0.00020001': '20020.00000000',
     '0.00020000': '45269.00000000',
     '0.00019990': '270.00000000',
     '0.00019880': '2117.00000000',
     '0.00019800': '1200.00000000',
     '0.00019783': '50.00000000',
     '0.00019702': '300.00000000',
     '0.00019686': '10.00000000',
     '0.00019600': '1025.00000000',
     '0.00019595': '139.00000000',
     '0.00019501': '3227.00000000',
     '0.00019500': '3832.00000000',
     '0.00019488': '82.00000000',
     '0.00019400': '1853.00000000',
     '0.00019293': '10.00000000',
     '0.00019289': '30.00000000',
     '0.00019234': '1999.00000000',
     '0.00019200': '4765.00000000',
     '0.00019190': '6.00000000',
     '0.00019100': '4353.00000000',
     '0.00019073': '12.00000000',
     '0.00019058': '28.00000000',
     '0.00019050': '718.00000000',
     '0.00019001': '20.00000000',
     '0.00019000': '39478.00000000',
     '0.00018907': '10.00000000',
     '0.00018888': '10045.00000000',
     '0.00018880': '15.00000000',
     '0.00018800': '3528.00000000',
     '0.00018700': '328.00000000',
     '0.00018600': '1000.00000000',
     '0.00018598': '2187.00000000',
     '0.00018538': '1383.00000000',
     '0.00018529': '10.00000000',
     '0.00018500': '1512.00000000',
     '0.00018253': '30.00000000',
     '0.00018200': '3000.00000000',
     '0.00018158': '10.00000000',
     '0.00018106': '250.00000000',
     '0.00018100': '4577.00000000',
     '0.00018011': '500.00000000',
     '0.00018000': '29832.00000000' },
  asks:
   { '0.00022999': '32.00000000',
     '0.00023086': '583.00000000',
     '0.00023095': '1154.00000000',
     '0.00023119': '781.00000000',
     '0.00023120': '3401.00000000',
     '0.00023180': '4889.00000000',
     '0.00023185': '83.00000000',
     '0.00023211': '750.00000000',
     '0.00023339': '9273.00000000',
     '0.00023340': '474.00000000',
     '0.00023440': '500.00000000',
     '0.00023450': '1433.00000000',
     '0.00023500': '1480.00000000',
     '0.00023573': '87.00000000',
     '0.00023580': '518.00000000',
     '0.00023999': '863.00000000',
     '0.00024000': '275.00000000',
     '0.00024100': '60.00000000',
     '0.00024119': '3736.00000000',
     '0.00024180': '989.00000000',
     '0.00024350': '1285.00000000',
     '0.00024399': '500.00000000',
     '0.00024400': '2964.00000000',
     '0.00024419': '500.00000000',
     '0.00024500': '4499.00000000',
     '0.00024580': '542.00000000',
     '0.00024584': '6.00000000',
     '0.00024700': '250.00000000',
     '0.00024789': '2938.00000000',
     '0.00024790': '5535.00000000',
     '0.00024800': '499.00000000',
     '0.00024892': '2000.00000000',
     '0.00024920': '652.00000000',
     '0.00024972': '9242.00000000',
     '0.00024999': '1262.00000000',
     '0.00025000': '3739.00000000',
     '0.00025078': '250.00000000',
     '0.00025348': '1000.00000000',
     '0.00025499': '220.00000000',
     '0.00025500': '6029.00000000',
     '0.00025518': '10.00000000',
     '0.00025698': '17.00000000',
     '0.00025700': '250.00000000',
     '0.00025800': '265.00000000',
     '0.00025925': '20.00000000',
     '0.00025984': '1048.00000000',
     '0.00025985': '1048.00000000',
     '0.00025987': '1165.00000000',
     '0.00025990': '465.00000000',
     '0.00025994': '571.00000000',
     '0.00025995': '390.00000000',
     '0.00026000': '5033.00000000',
     '0.00026028': '10.00000000',
     '0.00026280': '40.00000000',
     '0.00026300': '13.00000000',
     '0.00026348': '50.00000000',
     '0.00026500': '38.00000000',
     '0.00026548': '10.00000000',
     '0.00026594': '51.00000000',
     '0.00026666': '15000.00000000',
     '0.00026700': '500.00000000',
     '0.00026800': '27.00000000',
     '0.00026900': '1000.00000000',
     '0.00026929': '50.00000000',
     '0.00026990': '270.00000000',
     '0.00027000': '8750.00000000',
     '0.00027199': '50.00000000',
     '0.00027300': '351.00000000',
     '0.00027429': '50.00000000',
     '0.00027480': '270.00000000',
     '0.00027500': '38.00000000',
     '0.00027690': '242.00000000',
     '0.00027700': '500.00000000',
     '0.00027789': '1317.00000000',
     '0.00027906': '1457.00000000',
     '0.00027912': '98.00000000',
     '0.00027949': '50.00000000',
     '0.00027950': '2000.00000000',
     '0.00027977': '96.00000000',
     '0.00027980': '1031.00000000',
     '0.00028000': '782.00000000',
     '0.00028300': '25.00000000',
     '0.00028500': '48.00000000',
     '0.00028590': '364.00000000',
     '0.00028680': '50.00000000',
     '0.00028699': '50.00000000',
     '0.00028700': '1600.00000000',
     '0.00028800': '3509.00000000',
     '0.00028890': '175.00000000',
     '0.00028900': '11474.00000000',
     '0.00028999': '10000.00000000',
     '0.00029000': '623.00000000',
     '0.00029100': '303.00000000',
     '0.00029141': '456.00000000',
     '0.00029200': '9999.00000000',
     '0.00029234': '104.00000000',
     '0.00029300': '200.00000000',
     '0.00029358': '325.00000000',
     '0.00029399': '153.00000000',
     '0.00029428': '100.00000000' } }

Placing a LIMIT order

let quantity = 1, price = 0.069;
binance.buy("ETHBTC", quantity, price);
binance.sell("ETHBTC", quantity, price);

Placing a MARKET order

// These orders will be executed at current market price.
let quantity = 1;
binance.marketBuy("BNBBTC", quantity);
binance.marketSell("ETHBTC", quantity);

LIMIT order with callback

let quantity = 5, price = 0.00402030;
binance.buy("BNBETH", quantity, price, {type:'LIMIT'}, (error, response) => {
  console.info("Limit Buy response", response);
  console.info("order id: " + response.orderId);
});

View Response

Limit Buy response {
  symbol: 'BNBETH',
  orderId: 4480717,
  clientOrderId: 'te38xGILZUXrPZHnTQPH6h',
  transactTime: 1509049732437,
  price: '0.00402030',
  origQty: '5.00000000',
  executedQty: '5.00000000',
  status: 'FILLED',
  timeInForce: 'GTC',
  type: 'LIMIT',
  side: 'BUY' }
//order id: 4480717

Chaining orders together

let quantity = 1;
binance.marketBuy("BNBBTC", quantity, (error, response) => {
  console.info("Market Buy response", response);
  console.info("order id: " + response.orderId);
  // Now you can limit sell with a stop loss, etc.
});

View Response

Market Buy response {
  symbol: 'BNBETH',
  orderId: 4480553,
  clientOrderId: 'rCGiCG08PGy7AwvbrG5d83',
  transactTime: 1509049376261,
  price: '0.00000000',
  origQty: '1.00000000',
  exeutedQty: '1.00000000',
  status: 'FILLED',
  timeInForce: 'GTC',
  type: 'MARKET',
  side: 'BUY' }
//order id: 4480553

Placing a STOP LOSS order

// When the stop is reached, a stop order becomes a market order
// Note: You must also pass one of these type parameters:
// STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, TAKE_PROFIT_LIMIT
let type = "STOP_LOSS";
let quantity = 1;
let price = 0.069;
let stopPrice = 0.068;
binance.sell("ETHBTC", quantity, price, {stopPrice: stopPrice, type: type});

Placing an ICEBERG order

// Iceberg orders are intended to conceal the order quantity.
let quantity = 1;
let price = 0.069;
binance.sell("ETHBTC", quantity, price, {icebergQty: 10});

Cancel an order

binance.cancel("ETHBTC", orderid, (error, response, symbol) => {
  console.info(symbol+" cancel response:", response);
});

Cancel all open orders

console.info( await binance.cancelAll("XMRBTC") );

Get open orders for a symbol

binance.openOrders("ETHBTC", (error, openOrders, symbol) => {
  console.info("openOrders("+symbol+")", openOrders);
});

Get list of all open orders

binance.openOrders(false, (error, openOrders) => {
  console.info("openOrders()", openOrders);
});

Check an order's status

let orderid = "7610385";
binance.orderStatus("ETHBTC", orderid, (error, orderStatus, symbol) => {
  console.info(symbol+" order status:", orderStatus);
});

Get your Trade History

binance.trades("SNMBTC", (error, trades, symbol) => {
  console.info(symbol+" trade history", trades);
});

View Response

[ { id: 9572,
    orderId: 47884,
    price: '0.00003701',
    qty: '1467.00000000',
    commission: '0.06774660',
    commissionAsset: 'BNB',
    time: 1507062500456,
    isBuyer: true,
    isMaker: true,
    isBestMatch: true },
  { id: 9575,
    orderId: 47884,
    price: '0.00003701',
    qty: '735.00000000',
    commission: '0.03394257',
    commissionAsset: 'BNB',
    time: 1507062502528,
    isBuyer: true,
    isMaker: true,
    isBestMatch: true } } ]

Get all account orders; active, canceled, or filled.

binance.allOrders("ETHBTC", (error, orders, symbol) => {
  console.info(symbol+" orders:", orders);
});

Get dust log

binance.dustLog((error, dustlog) => {
  console.info(dustlog);
})

Get 24hr ticker price change statistics for all symbols

binance.prevDay(false, (error, prevDay) => {
  // console.info(prevDay); // view all data
  for ( let obj of prevDay ) {
    let symbol = obj.symbol;
    console.info(symbol+" volume:"+obj.volume+" change: "+obj.priceChangePercent+"%");
  }
});

Get 24hr ticker price change statistics for a symbol

binance.prevDay("BNBBTC", (error, prevDay, symbol) => {
  console.info(symbol+" previous day:", prevDay);
  console.info("BNB change since yesterday: "+prevDay.priceChangePercent+"%")
});

Get Kline/candlestick data for a symbol

You can use the optional API parameters for getting historical candlesticks, these are useful if you want to import data from earlier back in time. Optional parameters: limit (max/default 500), startTime, endTime.

// Intervals: 1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,1M
binance.candlesticks("BNBBTC", "5m", (error, ticks, symbol) => {
  console.info("candlesticks()", ticks);
  let last_tick = ticks[ticks.length - 1];
  let [time, open, high, low, close, volume, closeTime, assetVolume, trades, buyBaseVolume, buyAssetVolume, ignored] = last_tick;
  console.info(symbol+" last close: "+close);
}, {limit: 500, endTime: 1514764800000});

WebSockets Implementation

Get Complete WebSocket Chart Cache

This function pulls existing chart data before connecting to the WebSocket, and provides you realtime synchronized chart information including the most recent 500 candles.

binance.websockets.chart("BNBBTC", "1m", (symbol, interval, chart) => {
  let tick = binance.last(chart);
  const last = chart[tick].close;
  console.info(chart);
  // Optionally convert 'chart' object to array:
  // let ohlc = binance.ohlc(chart);
  // console.info(symbol, ohlc);
  console.info(symbol+" last price: "+last)
});

View Response

{
  '1517557800000':
   { open: '0.00100090',
     high: '0.00100650',
     low: '0.00099810',
     close: '0.00100370',
     volume: '1161.52000000' },
  '1517557860000':
   { open: '0.00100360',
     high: '0.00101010',
     low: '0.00100000',
     close: '0.00100310',
     volume: '1977.68000000' },
  '1517557920000':
   { open: '0.00100100',
     high: '0.00101130',
     low: '0.00100080',
     close: '0.00100670',
     volume: '2002.00000000' },
  '1517557980000':
   { open: '0.00100660',
     high: '0.00101400',
     low: '0.00100200',
     close: '0.00100640',
     volume: '3896.40000000' },
  '1517558040000':
   { open: '0.00100630',
     high: '0.00101390',
     low: '0.00100350',
     close: '0.00100470',
     volume: '1675.48000000' },
  '1517558100000':
   { open: '0.00100860',
     high: '0.00101450',
     low: '0.00100100',
     close: '0.00100270',
     volume: '1918.46000000' },
  '1517558160000':
   { open: '0.00100460',
     high: '0.00101480',
     low: '0.00100310',
     close: '0.00100670',
     volume: '2464.12000000' },
  '1517558220000':
   { open: '0.00100510',
     high: '0.00100660',
     low: '0.00100110',
     close: '0.00100250',
     volume: '1484.59000000' } }
// (..many more entries not shown)
///BNBBTC last price: 0.00100250

Get Candlestick Updates via WebSocket

// Periods: 1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,1M
binance.websockets.candlesticks(['BNBBTC'], "1m", (candlesticks) => {
  let { e:eventType, E:eventTime, s:symbol, k:ticks } = candlesticks;
  let { o:open, h:high, l:low, c:close, v:volume, n:trades, i:interval, x:isFinal, q:quoteVolume, V:buyVolume, Q:quoteBuyVolume } = ticks;
  console.info(symbol+" "+interval+" candlestick update");
  console.info("open: "+open);
  console.info("high: "+high);
  console.info("low: "+low);
  console.info("close: "+close);
  console.info("volume: "+volume);
  console.info("isFinal: "+isFinal);
});

Get Trade Updates via WebSocket

binance.websockets.trades(['BNBBTC', 'ETHBTC'], (trades) => {
  let {e:eventType, E:eventTime, s:symbol, p:price, q:quantity, m:maker, a:tradeId} = trades;
  console.info(symbol+" trade update. price: "+price+", quantity: "+quantity+", maker: "+maker);
});

Get miniTicker via WebSocket

binance.websockets.miniTicker(markets => {
  console.info(markets);
});

View Response

  ICXBNB:
   { close: '0.34803000',
     open: '0.34249000',
     high: '0.35000000',
     low: '0.31001000',
     volume: '134681.88000000',
     quoteVolume: '44351.78363150',
     eventTime: 1520501508957 },
  ELFETH:
   { close: '0.00120820',
     open: '0.00132816',
     high: '0.00132926',
     low: '0.00115888',
     volume: '852919.00000000',
     quoteVolume: '1045.37831133',
     eventTime: 1520501508735 },
  PIVXBTC:
   { close: '0.00049510',
     open: '0.00051000',
     high: '0.00056290',
     low: '0.00049200',
     volume: '215530.27000000',
     quoteVolume: '111.50245426',
     eventTime: 1520501508367 }

Get 24hr Price Change Statistics via WebSocket

// For all symbols:
binance.websockets.prevDay(false, (error, response) => {
  console.info(response);
});

// For a specific symbol:
binance.websockets.prevDay('BNBBTC', (error, response) => {
  console.info(response);
});

View Response

{ eventType: '24hrTicker',
  eventTime: 1512629577435,
  symbol: 'BNBBTC',
  priceChange: '-0.00002671',
  percentChange: '-12.844',
  averagePrice: '0.00019282',
  prevClose: '0.00020796',
  close: '0.00018125',
  closeQty: '55.00000000',
  bestBid: '0.00018038',
  bestBidQty: '580.00000000',
  bestAsk: '0.00018125',
  bestAskQty: '144.00000000',
  open: '0.00020796',
  high: '0.00021300',
  low: '0.00017555',
  volume: '3731915.00000000',
  quoteVolume: '719.59011818',
  openTime: 1512543177433,
  closeTime: 1512629577433,
  firstTradeId: 2248079,
  lastTradeId: 2284725,
  numTrades: 36647 }

Get Market Depth via WebSocket

binance.websockets.depth(['BNBBTC'], (depth) => {
  let {e:eventType, E:eventTime, s:symbol, u:updateId, b:bidDepth, a:askDepth} = depth;
  console.info(symbol+" market depth update");
  console.info(bidDepth, askDepth);
});

Maintain Market Depth Cache Locally via WebSocket

binance.websockets.depthCache(['BNBBTC'], (symbol, depth) => {
  let bids = binance.sortBids(depth.bids);
  let asks = binance.sortAsks(depth.asks);
  console.info(symbol+" depth cache update");
  console.info("bids", bids);
  console.info("asks", asks);
  console.info("best bid: "+binance.first(bids));
  console.info("best ask: "+binance.first(asks));
  console.info("last updated: " + new Date(depth.eventTime));
});

View Response

BNBBTC depth cache update
asks { '0.00025400': 0.531114,
  '0.00025440': 0.2602512,
  '0.00025469': 0.01400795,
  '0.00025500': 0.0051,
  '0.00025555': 0.0245328,
  '0.00025629': 0.05100171,
  '0.00025630': 0.0146091,
  '0.00025642': 0.02230854,
  '0.00025825': 0.00180775,
  '0.00025896': 0.21856224,
  '0.00025927': 0.025927 }
bids { '0.00025203': 0.201624,
  '0.00025202': 0.04838784,
  '0.00025200': 0.13482,
  '0.00025195': 0.01385725,
  '0.00025187': 0.25539618,
  '0.00025138': 0.012569,
  '0.00025136': 0.04247984,
  '0.00025135': 0.0085459,
  '0.00025100': 0.02259,
  '0.00025072': 0.012536,
  '0.00025071': 0.00401136 }
//best ask: 0.00025400
//best bid: 0.00025203
//last updated: Thu Apr 18 2019 00:52:49 GMT-0400 (Eastern Daylight Time)

bookTickers stream includes the bid/ask price & amount, for all symbols

binance.websockets.bookTickers( console.log );

bookTickers stream includes the bid/ask price & amount, for a symbol

binance.websockets.bookTickers( 'BTCUSDT', console.log );

Deposit & Withdraw

Get Deposit Address

binance.depositAddress("XMR", (error, response) => {
  console.info(response);
});

Get All Deposit History

binance.depositHistory((error, response) => {
  console.info(response);
});

Get Deposit History for a specific symbol

binance.depositHistory((error, response) => {
  console.info(response);
}, "VEN");

Get All Withdraw History

binance.withdrawHistory((error, response) => {
  console.info(response);
});

Get Withdraw History for a specific symbol

binance.withdrawHistory((error, response) => {
  console.info(response);
}, "BTC");

Withdraw with AddressTag

// Required for coins like XMR, XRP, etc.
let address = "44tLjmXrQNrWJ5NBsEj2R77ZBEgDa3fEe9GLpSf2FRmhexPvfYDUAB7EXX1Hdb3aMQ9FLqdJ56yaAhiXoRsceGJCRS3Jxkn";
let addressTag = "0e5e38a01058dbf64e53a4333a5acf98e0d5feb8e523d32e3186c664a9c762c1";
let amount = 0.1;
binance.withdraw("XMR", address, amount, addressTag);

Withdraw

binance.withdraw("BTC", "1C5gqLRs96Xq4V2ZZAR1347yUCpHie7sa", 0.2);

Binance Margin API

Transfer from Main account to Margin account

binance.mgTransferMainToMargin(asset, amount, (error, response) => {
    if ( error ) return console.warn(error);
    // Success! Transaction ID: response.tranId
});

Transfer from Margin account to Main account

binance.mgTransferMarginToMain(asset, amount, (error, response) => {
    if ( error ) return console.warn(error);
    // Success! Transaction ID: response.tranId
});

Get maximum transfer-out amount from Margin account to Main account

binance.maxTransferable(asset, (error, response) => {
    if ( error ) return console.warn(error);
    console.info(`Maximum transfer-out amount: ${response.amount}`);
});

Get maximum borrow amount

binance.maxBorrowable(asset, (error, response) => {
    if ( error ) return console.warn(error);
    console.info(`Maximum borrow amount: ${response.amount}`);
});

Borrow from margin account

binance.mgBorrow(asset, amount, (error, response) => {
    if ( error ) return console.warn(error);
    // Success! Transaction ID: response.tranId
});

Repay margin account

binance.mgRepay(asset, amount, (error, response) => {
    if ( error ) return console.warn(error);
    // Success! Transaction ID: response.tranId
});

Margin BUY and SELL orders

Instead of binance.buy() use binance.mgBuy() and instead of binance.sell() use binance.mgSell().

For market orders use binance.mgMarketBuy() and binance.mgMarketSell().

For order operations, use binance.mgCancel(), binance.mgCancelOrders(), binance.mgAllOrders(), binance.openOrders(), binance.mgOrderStatus().

Usage and callbacks are the same as the 'regular account' counterparts.

Margin account details

binance.mgAccount((error, response) => {
   if ( error ) return console.warn(error);
   console.info("Account details response:", response)
})

View response

  {
    borrowEnabled: true,
    marginLevel: '999.00000000',
    totalAssetOfBtc: '0.00000003',
    totalLiabilityOfBtc: '0.00000000',
    totalNetAssetOfBtc: '0.00000003',
    tradeEnabled: true,
    transferEnabled: true,
    userAssets: [
      {
        asset: 'MATIC',
        borrowed: '0.00000000',
        free: '0.00000000',
        interest: '0.00000000',
        locked: '0.00000000',
        netAsset: '0.00000000'
      }
    ]
  }

Binance Lending API

Lending Account Details

let lendingData = await binance.lending();

View response

  lendingData {
    positionAmountVos: [
      {
        amount: '952983.20208997',
        amountInBTC: '129.54853649',
        amountInUSDT: '952983.20208997',
        asset: 'USDT'
      }
    ],
    totalAmountInBTC: '129.54853649',
    totalAmountInUSDT: '952983.20208997',
    totalFixedAmountInBTC: '13.59400000',
    totalFixedAmountInUSDT: '100000.00000000',
    totalFlexibleInBTC: '115.95453649',
    totalFlexibleInUSDT: '852983.20208997'
  }
  {
    positionAmountVos: [],
    totalAmountInBTC: '0.00000000',
    totalAmountInUSDT: '0.00000000',
    totalFixedAmountInBTC: '0.00000000',
    totalFixedAmountInUSDT: '0.00000000',
    totalFlexibleInBTC: '0.00000000',
    totalFlexibleInUSDT: '0.00000000'
  }
  {
    positionAmountVos: [],
    totalAmountInBTC: '0.00000000',
    totalAmountInUSDT: '0.00000000',
    totalFixedAmountInBTC: '0.00000000',
    totalFixedAmountInUSDT: '0.00000000',
    totalFlexibleInBTC: '0.00000000',
    totalFlexibleInUSDT: '0.00000000'
  }

Advanced Examples

exchangeInfo: Pull minimum order size, quantity, etc
Clamp order quantities to required amounts via minQty, minNotional, stepSize when placing orders
Show API Rate limits
Connect to all WebSockets at once
Get last order for a symbol
newOrderRespType example
Recent Trades (historicalTrades, recentTrades, aggTrades functions)
Terminate WebSocket connections
User Data: Account Balance Updates, Trade Updates, New Orders, Filled Orders, Cancelled Orders via WebSocket Margin User Data: Account Balance Updates, Trade Updates, New Orders, Filled Orders, Cancelled Orders via WebSocket Asynchronous Syntax Options

Troubleshooting

Verify that your system time is correct. If you have any suggestions don't hesitate to file an issue.

Having problems? Try adding useServerTime to your options or setting recvWindow:

binance.options({
  APIKEY: 'xxx',
  APISECRET: 'xxx',
  useServerTime: true,
  recvWindow: 60000, // Set a higher recvWindow to increase response timeout
  verbose: true, // Add extra output when subscribing to WebSockets, etc
  log: log => {
    console.log(log); // You can create your own logger here, or disable console output
  }
});

Problems getting your balance? Wrap the entry point of your application in useServerTime:

await binance.useServerTime();
binance.balance((error, balances) => {
    if ( error ) return console.error(error);
    console.info("balances()", balances);
    console.info("BNB balance: ", balances.BNB.available);
});

You can enable verbose mode to help with debugging WebSocket streams:

binance.setOption( 'verbose', true );

Download Details:
Author: binance-exchange
Source Code: https://github.com/binance-exchange/node-binance-api
License: MIT license

#Binance #blockchain #node #api #javascript

Node Binance API: an Asynchronous Node.js Library for The Binance API