1# LibUV in Lua 2 3The [luv][] project provides access to the multi-platform support library 4[libuv][] in Lua code. It was primarily developed for the [luvit][] project as 5the built-in `uv` module, but can be used in other Lua environments. 6 7More information about the core libuv library can be found at the original 8[libuv documentation page][]. 9 10### TCP Echo Server Example 11 12Here is a small example showing a TCP echo server: 13 14```lua 15local uv = require("luv") -- "luv" when stand-alone, "uv" in luvi apps 16 17local server = uv.new_tcp() 18server:bind("127.0.0.1", 1337) 19server:listen(128, function (err) 20 assert(not err, err) 21 local client = uv.new_tcp() 22 server:accept(client) 23 client:read_start(function (err, chunk) 24 assert(not err, err) 25 if chunk then 26 client:write(chunk) 27 else 28 client:shutdown() 29 client:close() 30 end 31 end) 32end) 33print("TCP server listening at 127.0.0.1 port 1337") 34uv.run() -- an explicit run call is necessary outside of luvit 35``` 36 37### Module Layout 38 39The luv library contains a single Lua module referred to hereafter as `uv` for 40simplicity. This module consists mostly of functions with names corresponding to 41their original libuv versions. For example, the libuv function `uv_tcp_bind` has 42a luv version at `uv.tcp_bind`. Currently, only one non-function field exists: 43`uv.constants`, which is a table. 44 45### Functions vs Methods 46 47In addition to having simple functions, luv provides an optional method-style 48API. For example, `uv.tcp_bind(server, host, port)` can alternatively be called 49as `server:bind(host, port)`. Note that the first argument `server` becomes the 50object and `tcp_` is removed from the function name. Method forms are 51documented below where they exist. 52 53### Synchronous vs Asynchronous Functions 54 55Functions that accept a callback are asynchronous. These functions may 56immediately return results to the caller to indicate their initial status, but 57their final execution is deferred until at least the next libuv loop iteration. 58After completion, their callbacks are executed with any results passed to it. 59 60Functions that do not accept a callback are synchronous. These functions 61immediately return their results to the caller. 62 63Some (generally FS and DNS) functions can behave either synchronously or 64asynchronously. If a callback is provided to these functions, they behave 65asynchronously; if no callback is provided, they behave synchronously. 66 67### Pseudo-Types 68 69Some unique types are defined. These are not actual types in Lua, but they are 70used here to facilitate documenting consistent behavior: 71- `fail`: an assertable `nil, string, string` tuple (see [Error handling][]) 72- `callable`: a `function`; or a `table` or `userdata` with a `__call` 73 metamethod 74- `buffer`: a `string` or a sequential `table` of `string`s 75- `threadargs`: variable arguments (`...`) of type `nil`, `boolean`, `number`, 76 `string`, or `userdata` 77 78## Contents 79 80This documentation is mostly a retelling of the [libuv API documentation][] 81within the context of luv's Lua API. Low-level implementation details and 82unexposed C functions and types are not documented here except for when they 83are relevant to behavior seen in the Lua module. 84 85- [Error handling][] 86- [Version checking][] 87- [`uv_loop_t`][] — Event loop 88- [`uv_req_t`][] — Base request 89- [`uv_handle_t`][] — Base handle 90 - [`uv_timer_t`][] — Timer handle 91 - [`uv_prepare_t`][] — Prepare handle 92 - [`uv_check_t`][] — Check handle 93 - [`uv_idle_t`][] — Idle handle 94 - [`uv_async_t`][] — Async handle 95 - [`uv_poll_t`][] — Poll handle 96 - [`uv_signal_t`][] — Signal handle 97 - [`uv_process_t`][] — Process handle 98 - [`uv_stream_t`][] — Stream handle 99 - [`uv_tcp_t`][] — TCP handle 100 - [`uv_pipe_t`][] — Pipe handle 101 - [`uv_tty_t`][] — TTY handle 102 - [`uv_udp_t`][] — UDP handle 103 - [`uv_fs_event_t`][] — FS Event handle 104 - [`uv_fs_poll_t`][] — FS Poll handle 105- [File system operations][] 106- [Thread pool work scheduling][] 107- [DNS utility functions][] 108- [Threading and synchronization utilities][] 109- [Miscellaneous utilities][] 110- [Metrics operations][] 111 112## Error Handling 113 114[Error handling]: #error-handling 115 116In libuv, errors are negative numbered constants; however, these errors and the 117functions used to handle them are not exposed to luv users. Instead, if an 118internal error is encountered, the luv function will return to the caller an 119assertable `nil, err, name` tuple. 120 121- `nil` idiomatically indicates failure 122- `err` is a string with the format `{name}: {message}` 123 - `{name}` is the error name provided internally by `uv_err_name` 124 - `{message}` is a human-readable message provided internally by `uv_strerror` 125- `name` is the same string used to construct `err` 126 127This tuple is referred to below as the `fail` pseudo-type. 128 129When a function is called successfully, it will return either a value that is 130relevant to the operation of the function, or the integer `0` to indicate 131success, or sometimes nothing at all. These cases are documented below. 132 133## Version Checking 134 135[Version checking]: #version-checking 136 137### `uv.version()` 138 139Returns the libuv version packed into a single integer. 8 bits are used for each 140component, with the patch number stored in the 8 least significant bits. For 141example, this would be 0x010203 in libuv 1.2.3. 142 143**Returns:** `integer` 144 145### `uv.version_string()` 146 147Returns the libuv version number as a string. For example, this would be "1.2.3" 148in libuv 1.2.3. For non-release versions, the version suffix is included. 149 150**Returns:** `string` 151 152## `uv_loop_t` — Event loop 153 154[`uv_loop_t`]: #uv_loop_t--event-loop 155 156The event loop is the central part of libuv's functionality. It takes care of 157polling for I/O and scheduling callbacks to be run based on different sources of 158events. 159 160In luv, there is an implicit uv loop for every Lua state that loads the library. 161You can use this library in an multi-threaded environment as long as each thread 162has it's own Lua state with its corresponding own uv loop. This loop is not 163directly exposed to users in the Lua module. 164 165### `uv.loop_close()` 166 167Closes all internal loop resources. In normal execution, the loop will 168automatically be closed when it is garbage collected by Lua, so it is not 169necessary to explicitly call `loop_close()`. Call this function only after the 170loop has finished executing and all open handles and requests have been closed, 171or it will return `EBUSY`. 172 173**Returns:** `0` or `fail` 174 175### `uv.run([mode])` 176 177**Parameters:** 178- `mode`: `string` or `nil` (default: `"default"`) 179 180This function runs the event loop. It will act differently depending on the 181specified mode: 182 183 - `"default"`: Runs the event loop until there are no more active and 184 referenced handles or requests. Returns `true` if `uv.stop()` was called and 185 there are still active handles or requests. Returns `false` in all other 186 cases. 187 188 - `"once"`: Poll for I/O once. Note that this function blocks if there are no 189 pending callbacks. Returns `false` when done (no active handles or requests 190 left), or `true` if more callbacks are expected (meaning you should run the 191 event loop again sometime in the future). 192 193 - `"nowait"`: Poll for I/O once but don't block if there are no pending 194 callbacks. Returns `false` if done (no active handles or requests left), 195 or `true` if more callbacks are expected (meaning you should run the event 196 loop again sometime in the future). 197 198**Returns:** `boolean` or `fail` 199 200**Note:** Luvit will implicitly call `uv.run()` after loading user code, but if 201you use the luv bindings directly, you need to call this after registering 202your initial set of event callbacks to start the event loop. 203 204### `uv.loop_configure(option, ...)` 205 206**Parameters:** 207- `option`: `string` 208- `...`: depends on `option`, see below 209 210Set additional loop options. You should normally call this before the first call 211to uv_run() unless mentioned otherwise. 212 213Supported options: 214 215 - `"block_signal"`: Block a signal when polling for new events. The second argument 216 to loop_configure() is the signal name (as a lowercase string) or the signal number. 217 This operation is currently only implemented for `"sigprof"` signals, to suppress 218 unnecessary wakeups when using a sampling profiler. Requesting other signals will 219 fail with `EINVAL`. 220 - `"metrics_idle_time"`: Accumulate the amount of idle time the event loop spends 221 in the event provider. This option is necessary to use `metrics_idle_time()`. 222 223An example of a valid call to this function is: 224 225```lua 226uv.loop_configure("block_signal", "sigprof") 227``` 228 229**Returns:** `0` or `fail` 230 231**Note:** Be prepared to handle the `ENOSYS` error; it means the loop option is 232not supported by the platform. 233 234### `uv.loop_mode()` 235 236If the loop is running, returns a string indicating the mode in use. If the loop 237is not running, `nil` is returned instead. 238 239**Returns:** `string` or `nil` 240 241### `uv.loop_alive()` 242 243Returns `true` if there are referenced active handles, active requests, or 244closing handles in the loop; otherwise, `false`. 245 246**Returns:** `boolean` or `fail` 247 248### `uv.stop()` 249 250Stop the event loop, causing `uv.run()` to end as soon as possible. This 251will happen not sooner than the next loop iteration. If this function was called 252before blocking for I/O, the loop won't block for I/O on this iteration. 253 254**Returns:** Nothing. 255 256### `uv.backend_fd()` 257 258Get backend file descriptor. Only kqueue, epoll, and event ports are supported. 259 260This can be used in conjunction with `uv.run("nowait")` to poll in one thread 261and run the event loop's callbacks in another 262 263**Returns:** `integer` or `nil` 264 265**Note**: Embedding a kqueue fd in another kqueue pollset doesn't work on all 266platforms. It's not an error to add the fd but it never generates events. 267 268### `uv.backend_timeout()` 269 270Get the poll timeout. The return value is in milliseconds, or -1 for no timeout. 271 272**Returns:** `integer` 273 274### `uv.now()` 275 276Returns the current timestamp in milliseconds. The timestamp is cached at the 277start of the event loop tick, see `uv.update_time()` for details and rationale. 278 279The timestamp increases monotonically from some arbitrary point in time. Don't 280make assumptions about the starting point, you will only get disappointed. 281 282**Returns:** `integer` 283 284**Note**: Use `uv.hrtime()` if you need sub-millisecond granularity. 285 286### `uv.update_time()` 287 288Update the event loop's concept of "now". Libuv caches the current time at the 289start of the event loop tick in order to reduce the number of time-related 290system calls. 291 292You won't normally need to call this function unless you have callbacks that 293block the event loop for longer periods of time, where "longer" is somewhat 294subjective but probably on the order of a millisecond or more. 295 296**Returns:** Nothing. 297 298### `uv.walk(callback)` 299 300**Parameters:** 301- `callback`: `callable` 302 - `handle`: `userdata` for sub-type of `uv_handle_t` 303 304Walk the list of handles: `callback` will be executed with each handle. 305 306**Returns:** Nothing. 307 308```lua 309-- Example usage of uv.walk to close all handles that aren't already closing. 310uv.walk(function (handle) 311 if not handle:is_closing() then 312 handle:close() 313 end 314end) 315``` 316 317## `uv_req_t` — Base request 318 319[`uv_req_t`]: #uv_req_t--request-handle 320 321`uv_req_t` is the base type for all libuv request types. 322 323### `uv.cancel(req)` 324 325> method form `req:cancel()` 326 327**Parameters:** 328- `req`: `userdata` for sub-type of `uv_req_t` 329 330Cancel a pending request. Fails if the request is executing or has finished 331executing. Only cancellation of `uv_fs_t`, `uv_getaddrinfo_t`, 332`uv_getnameinfo_t` and `uv_work_t` requests is currently supported. 333 334**Returns:** `0` or `fail` 335 336### `uv.req_get_type(req)` 337 338> method form `req:get_type()` 339 340**Parameters:** 341- `req`: `userdata` for sub-type of `uv_req_t` 342 343Returns the name of the struct for a given request (e.g. `"fs"` for `uv_fs_t`) 344and the libuv enum integer for the request's type (`uv_req_type`). 345 346**Returns:** `string, integer` 347 348## `uv_handle_t` — Base handle 349 350[`uv_handle_t`]: #uv_handle_t--base-handle 351 352`uv_handle_t` is the base type for all libuv handle types. All API functions 353defined here work with any handle type. 354 355### `uv.is_active(handle)` 356 357> method form `handle:is_active()` 358 359**Parameters:** 360- `handle`: `userdata` for sub-type of `uv_handle_t` 361 362Returns `true` if the handle is active, `false` if it's inactive. What "active” 363means depends on the type of handle: 364 365 - A [`uv_async_t`][] handle is always active and cannot be deactivated, except 366 by closing it with `uv.close()`. 367 368 - A [`uv_pipe_t`][], [`uv_tcp_t`][], [`uv_udp_t`][], etc. handle - basically 369 any handle that deals with I/O - is active when it is doing something that 370 involves I/O, like reading, writing, connecting, accepting new connections, 371 etc. 372 373 - A [`uv_check_t`][], [`uv_idle_t`][], [`uv_timer_t`][], etc. handle is active 374 when it has been started with a call to `uv.check_start()`, `uv.idle_start()`, 375 `uv.timer_start()` etc. until it has been stopped with a call to its 376 respective stop function. 377 378**Returns:** `boolean` or `fail` 379 380### `uv.is_closing(handle)` 381 382> method form `handle:is_closing()` 383 384**Parameters:** 385- `handle`: `userdata` for sub-type of `uv_handle_t` 386 387Returns `true` if the handle is closing or closed, `false` otherwise. 388 389**Returns:** `boolean` or `fail` 390 391**Note**: This function should only be used between the initialization of the 392handle and the arrival of the close callback. 393 394### `uv.close(handle, [callback])` 395 396> method form `handle:close([callback])` 397 398**Parameters:** 399- `handle`: `userdata` for sub-type of `uv_handle_t` 400- `callback`: `callable` or `nil` 401 402Request handle to be closed. `callback` will be called asynchronously after this 403call. This MUST be called on each handle before memory is released. 404 405Handles that wrap file descriptors are closed immediately but `callback` will 406still be deferred to the next iteration of the event loop. It gives you a chance 407to free up any resources associated with the handle. 408 409In-progress requests, like `uv_connect_t` or `uv_write_t`, are cancelled and 410have their callbacks called asynchronously with `ECANCELED`. 411 412**Returns:** Nothing. 413 414### `uv.ref(handle)` 415 416> method form `handle:ref()` 417 418**Parameters:** 419- `handle`: `userdata` for sub-type of `uv_handle_t` 420 421Reference the given handle. References are idempotent, that is, if a handle is 422already referenced calling this function again will have no effect. 423 424**Returns:** Nothing. 425 426See [Reference counting][]. 427 428### `uv.unref(handle)` 429 430> method form `handle:unref()` 431 432**Parameters:** 433- `handle`: `userdata` for sub-type of `uv_handle_t` 434 435Un-reference the given handle. References are idempotent, that is, if a handle 436is not referenced calling this function again will have no effect. 437 438**Returns:** Nothing. 439 440See [Reference counting][]. 441 442### `uv.has_ref(handle)` 443 444> method form `handle:has_ref()` 445 446**Parameters:** 447- `handle`: `userdata` for sub-type of `uv_handle_t` 448 449Returns `true` if the handle referenced, `false` if not. 450 451**Returns:** `boolean` or `fail` 452 453See [Reference counting][]. 454 455### `uv.send_buffer_size(handle, [size])` 456 457> method form `handle:send_buffer_size([size])` 458 459**Parameters:** 460- `handle`: `userdata` for sub-type of `uv_handle_t` 461- `size`: `integer` or `nil` (default: `0`) 462 463Gets or sets the size of the send buffer that the operating system uses for the 464socket. 465 466If `size` is omitted (or `0`), this will return the current send buffer size; otherwise, this will use `size` to set the new send buffer size. 467 468This function works for TCP, pipe and UDP handles on Unix and for TCP and UDP 469handles on Windows. 470 471**Returns:** 472- `integer` or `fail` (if `size` is `nil` or `0`) 473- `0` or `fail` (if `size` is not `nil` and not `0`) 474 475**Note**: Linux will set double the size and return double the size of the 476original set value. 477 478### `uv.recv_buffer_size(handle, [size])` 479 480> method form `handle:recv_buffer_size([size])` 481 482**Parameters:** 483- `handle`: `userdata` for sub-type of `uv_handle_t` 484- `size`: `integer` or `nil` (default: `0`) 485 486Gets or sets the size of the receive buffer that the operating system uses for 487the socket. 488 489If `size` is omitted (or `0`), this will return the current send buffer size; otherwise, this will use `size` to set the new send buffer size. 490 491This function works for TCP, pipe and UDP handles on Unix and for TCP and UDP 492handles on Windows. 493 494**Returns:** 495- `integer` or `fail` (if `size` is `nil` or `0`) 496- `0` or `fail` (if `size` is not `nil` and not `0`) 497 498**Note**: Linux will set double the size and return double the size of the 499original set value. 500 501### `uv.fileno(handle)` 502 503> method form `handle:fileno()` 504 505**Parameters:** 506- `handle`: `userdata` for sub-type of `uv_handle_t` 507 508Gets the platform dependent file descriptor equivalent. 509 510The following handles are supported: TCP, pipes, TTY, UDP and poll. Passing any 511other handle type will fail with `EINVAL`. 512 513If a handle doesn't have an attached file descriptor yet or the handle itself 514has been closed, this function will return `EBADF`. 515 516**Returns:** `integer` or `fail` 517 518**Warning**: Be very careful when using this function. libuv assumes it's in 519control of the file descriptor so any change to it may lead to malfunction. 520 521### `uv.handle_get_type(handle)` 522 523> method form `handle:get_type()` 524 525**Parameters:** 526- `handle`: `userdata` for sub-type of `uv_handle_t` 527 528Returns the name of the struct for a given handle (e.g. `"pipe"` for `uv_pipe_t`) 529and the libuv enum integer for the handle's type (`uv_handle_type`). 530 531**Returns:** `string, integer` 532 533## Reference counting 534 535[reference counting]: #reference-counting 536 537The libuv event loop (if run in the default mode) will run until there are no 538active and referenced handles left. The user can force the loop to exit early by 539unreferencing handles which are active, for example by calling `uv.unref()` 540after calling `uv.timer_start()`. 541 542A handle can be referenced or unreferenced, the refcounting scheme doesn't use a 543counter, so both operations are idempotent. 544 545All handles are referenced when active by default, see `uv.is_active()` for a 546more detailed explanation on what being active involves. 547 548## `uv_timer_t` — Timer handle 549 550[`uv_timer_t`]: #uv_timer_t--timer-handle 551 552> [`uv_handle_t`][] functions also apply. 553 554Timer handles are used to schedule callbacks to be called in the future. 555 556### `uv.new_timer()` 557 558Creates and initializes a new `uv_timer_t`. Returns the Lua userdata wrapping 559it. 560 561**Returns:** `uv_timer_t userdata` or `fail` 562 563```lua 564-- Creating a simple setTimeout wrapper 565local function setTimeout(timeout, callback) 566 local timer = uv.new_timer() 567 timer:start(timeout, 0, function () 568 timer:stop() 569 timer:close() 570 callback() 571 end) 572 return timer 573end 574 575-- Creating a simple setInterval wrapper 576local function setInterval(interval, callback) 577 local timer = uv.new_timer() 578 timer:start(interval, interval, function () 579 callback() 580 end) 581 return timer 582end 583 584-- And clearInterval 585local function clearInterval(timer) 586 timer:stop() 587 timer:close() 588end 589``` 590 591### `uv.timer_start(timer, timeout, repeat, callback)` 592 593> method form `timer:start(timeout, repeat, callback)` 594 595**Parameters:** 596- `timer`: `uv_timer_t userdata` 597- `timeout`: `integer` 598- `repeat`: `integer` 599- `callback`: `callable` 600 601Start the timer. `timeout` and `repeat` are in milliseconds. 602 603If `timeout` is zero, the callback fires on the next event loop iteration. If 604`repeat` is non-zero, the callback fires first after `timeout` milliseconds and 605then repeatedly after `repeat` milliseconds. 606 607**Returns:** `0` or `fail` 608 609### `uv.timer_stop(timer)` 610 611> method form `timer:stop()` 612 613**Parameters:** 614- `timer`: `uv_timer_t userdata` 615 616Stop the timer, the callback will not be called anymore. 617 618**Returns:** `0` or `fail` 619 620### `uv.timer_again(timer)` 621 622> method form `timer:again()` 623 624**Parameters:** 625- `timer`: `uv_timer_t userdata` 626 627Stop the timer, and if it is repeating restart it using the repeat value as the 628timeout. If the timer has never been started before it raises `EINVAL`. 629 630**Returns:** `0` or `fail` 631 632### `uv.timer_set_repeat(timer, repeat)` 633 634> method form `timer:set_repeat(repeat)` 635 636**Parameters:** 637- `timer`: `uv_timer_t userdata` 638- `repeat`: `integer` 639 640Set the repeat interval value in milliseconds. The timer will be scheduled to 641run on the given interval, regardless of the callback execution duration, and 642will follow normal timer semantics in the case of a time-slice overrun. 643 644For example, if a 50 ms repeating timer first runs for 17 ms, it will be 645scheduled to run again 33 ms later. If other tasks consume more than the 33 ms 646following the first timer callback, then the callback will run as soon as 647possible. 648 649**Returns:** Nothing. 650 651### `uv.timer_get_repeat(timer)` 652 653> method form `timer:get_repeat()` 654 655**Parameters:** 656- `timer`: `uv_timer_t userdata` 657 658Get the timer repeat value. 659 660**Returns:** `integer` 661 662### `uv.timer_get_due_in(timer)` 663 664> method form `timer:get_due_in()` 665 666**Parameters:** 667- `timer`: `uv_timer_t userdata` 668 669Get the timer due value or 0 if it has expired. The time is relative to `uv.now()`. 670 671**Returns:** `integer` 672 673**Note**: New in libuv version 1.40.0. 674 675## `uv_prepare_t` — Prepare handle 676 677[`uv_prepare_t`]: #uv_prepare_t--prepare-handle 678 679> [`uv_handle_t`][] functions also apply. 680 681Prepare handles will run the given callback once per loop iteration, right 682before polling for I/O. 683 684```lua 685local prepare = uv.new_prepare() 686prepare:start(function() 687 print("Before I/O polling") 688end) 689``` 690 691### `uv.new_prepare()` 692 693Creates and initializes a new `uv_prepare_t`. Returns the Lua userdata wrapping 694it. 695 696**Returns:** `uv_prepare_t userdata` or `fail` 697 698### `uv.prepare_start(prepare, callback)` 699 700> method form `prepare:start(callback)` 701 702**Parameters:** 703- `prepare`: `uv_prepare_t userdata` 704- `callback`: `callable` 705 706Start the handle with the given callback. 707 708**Returns:** `0` or `fail` 709 710### `uv.prepare_stop(prepare)` 711 712> method form `prepare:stop()` 713 714**Parameters:** 715- `prepare`: `uv_prepare_t userdata` 716 717Stop the handle, the callback will no longer be called. 718 719**Returns:** `0` or `fail` 720 721## `uv_check_t` — Check handle 722 723[`uv_check_t`]: #uv_check_t--check-handle 724 725> [`uv_handle_t`][] functions also apply. 726 727Check handles will run the given callback once per loop iteration, right after 728polling for I/O. 729 730```lua 731local check = uv.new_check() 732check:start(function() 733 print("After I/O polling") 734end) 735``` 736 737### `uv.new_check()` 738 739Creates and initializes a new `uv_check_t`. Returns the Lua userdata wrapping 740it. 741 742**Returns:** `uv_check_t userdata` or `fail` 743 744### `uv.check_start(check, callback)` 745 746> method form `check:start(callback)` 747 748**Parameters:** 749- `check`: `uv_check_t userdata` 750- `callback`: `callable` 751 752Start the handle with the given callback. 753 754**Returns:** `0` or `fail` 755 756### `uv.check_stop(check)` 757 758> method form `check:stop()` 759 760**Parameters:** 761- `check`: `uv_check_t userdata` 762 763Stop the handle, the callback will no longer be called. 764 765**Returns:** `0` or `fail` 766 767## `uv_idle_t` — Idle handle 768 769[`uv_idle_t`]: #uv_idle_t--idle-handle 770 771> [`uv_handle_t`][] functions also apply. 772 773Idle handles will run the given callback once per loop iteration, right before 774the [`uv_prepare_t`][] handles. 775 776**Note**: The notable difference with prepare handles is that when there are 777active idle handles, the loop will perform a zero timeout poll instead of 778blocking for I/O. 779 780**Warning**: Despite the name, idle handles will get their callbacks called on 781every loop iteration, not when the loop is actually "idle". 782 783```lua 784local idle = uv.new_idle() 785idle:start(function() 786 print("Before I/O polling, no blocking") 787end) 788``` 789 790### `uv.new_idle()` 791 792Creates and initializes a new `uv_idle_t`. Returns the Lua userdata wrapping 793it. 794 795**Returns:** `uv_idle_t userdata` or `fail` 796 797### `uv.idle_start(idle, callback)` 798 799> method form `idle:start(callback)` 800 801**Parameters:** 802- `idle`: `uv_idle_t userdata` 803- `callback`: `callable` 804 805Start the handle with the given callback. 806 807**Returns:** `0` or `fail` 808 809### `uv.idle_stop(check)` 810 811> method form `idle:stop()` 812 813**Parameters:** 814- `idle`: `uv_idle_t userdata` 815 816Stop the handle, the callback will no longer be called. 817 818**Returns:** `0` or `fail` 819 820## `uv_async_t` — Async handle 821 822[`uv_async_t`]: #uv_async_t--async-handle 823 824> [`uv_handle_t`][] functions also apply. 825 826Async handles allow the user to "wakeup" the event loop and get a callback 827called from another thread. 828 829```lua 830local async 831async = uv.new_async(function() 832 print("async operation ran") 833 async:close() 834end) 835 836async:send() 837``` 838 839### `uv.new_async([callback])` 840 841**Parameters:** 842- `callback`: `callable` or `nil` 843 - `...`: `threadargs` passed to/from `uv.async_send(async, ...)` 844 845Creates and initializes a new `uv_async_t`. Returns the Lua userdata wrapping 846it. A `nil` callback is allowed. 847 848**Returns:** `uv_async_t userdata` or `fail` 849 850**Note**: Unlike other handle initialization functions, this immediately starts 851the handle. 852 853### `uv.async_send(async, ...)` 854 855> method form `async:send(...)` 856 857**Parameters:** 858- `async`: `uv_async_t userdata` 859- `...`: `threadargs` 860 861Wakeup the event loop and call the async handle's callback. 862 863**Returns:** `0` or `fail` 864 865**Note**: It's safe to call this function from any thread. The callback will be 866called on the loop thread. 867 868**Warning**: libuv will coalesce calls to `uv.async_send(async)`, that is, not 869every call to it will yield an execution of the callback. For example: if 870`uv.async_send()` is called 5 times in a row before the callback is called, the 871callback will only be called once. If `uv.async_send()` is called again after 872the callback was called, it will be called again. 873 874## `uv_poll_t` — Poll handle 875 876[`uv_poll_t`]: #uv_poll_t--poll-handle 877 878> [`uv_handle_t`][] functions also apply. 879 880Poll handles are used to watch file descriptors for readability and writability, 881similar to the purpose of [poll(2)](http://linux.die.net/man/2/poll). 882 883The purpose of poll handles is to enable integrating external libraries that 884rely on the event loop to signal it about the socket status changes, like c-ares 885or libssh2. Using `uv_poll_t` for any other purpose is not recommended; 886`uv_tcp_t`, `uv_udp_t`, etc. provide an implementation that is faster and more 887scalable than what can be achieved with `uv_poll_t`, especially on Windows. 888 889It is possible that poll handles occasionally signal that a file descriptor is 890readable or writable even when it isn't. The user should therefore always be 891prepared to handle EAGAIN or equivalent when it attempts to read from or write 892to the fd. 893 894It is not okay to have multiple active poll handles for the same socket, this 895can cause libuv to busyloop or otherwise malfunction. 896 897The user should not close a file descriptor while it is being polled by an 898active poll handle. This can cause the handle to report an error, but it might 899also start polling another socket. However the fd can be safely closed 900immediately after a call to `uv.poll_stop()` or `uv.close()`. 901 902**Note**: On windows only sockets can be polled with poll handles. On Unix any 903file descriptor that would be accepted by poll(2) can be used. 904 905### `uv.new_poll(fd)` 906 907**Parameters:** 908- `fd`: `integer` 909 910Initialize the handle using a file descriptor. 911 912The file descriptor is set to non-blocking mode. 913 914**Returns:** `uv_poll_t userdata` or `fail` 915 916### `uv.new_socket_poll(fd)` 917 918**Parameters:** 919- `fd`: `integer` 920 921Initialize the handle using a socket descriptor. On Unix this is identical to 922`uv.new_poll()`. On windows it takes a SOCKET handle. 923 924The socket is set to non-blocking mode. 925 926**Returns:** `uv_poll_t userdata` or `fail` 927 928### `uv.poll_start(poll, events, callback)` 929 930> method form `poll:start(events, callback)` 931 932**Parameters:** 933- `poll`: `uv_poll_t userdata` 934- `events`: `string` or `nil` (default: `"rw"`) 935- `callback`: `callable` 936 - `err`: `nil` or `string` 937 - `events`: `string` or `nil` 938 939Starts polling the file descriptor. `events` are: `"r"`, `"w"`, `"rw"`, `"d"`, 940`"rd"`, `"wd"`, `"rwd"`, `"p"`, `"rp"`, `"wp"`, `"rwp"`, `"dp"`, `"rdp"`, 941`"wdp"`, or `"rwdp"` where `r` is `READABLE`, `w` is `WRITABLE`, `d` is 942`DISCONNECT`, and `p` is `PRIORITIZED`. As soon as an event is detected 943the callback will be called with status set to 0, and the detected events set on 944the events field. 945 946The user should not close the socket while the handle is active. If the user 947does that anyway, the callback may be called reporting an error status, but this 948is not guaranteed. 949 950**Returns:** `0` or `fail` 951 952**Note** Calling `uv.poll_start()` on a handle that is already active is fine. 953Doing so will update the events mask that is being watched for. 954 955### `uv.poll_stop(poll)` 956 957> method form `poll:stop()` 958 959**Parameters:** 960- `poll`: `uv_poll_t userdata` 961 962Stop polling the file descriptor, the callback will no longer be called. 963 964**Returns:** `0` or `fail` 965 966## `uv_signal_t` — Signal handle 967 968[`uv_signal_t`]: #uv_signal_t--signal-handle 969 970> [`uv_handle_t`][] functions also apply. 971 972Signal handles implement Unix style signal handling on a per-event loop bases. 973 974**Windows Notes:** 975 976Reception of some signals is emulated on Windows: 977 - SIGINT is normally delivered when the user presses CTRL+C. However, like on 978 Unix, it is not generated when terminal raw mode is enabled. 979 - SIGBREAK is delivered when the user pressed CTRL + BREAK. 980 - SIGHUP is generated when the user closes the console window. On SIGHUP the 981 program is given approximately 10 seconds to perform cleanup. After that 982 Windows will unconditionally terminate it. 983 - SIGWINCH is raised whenever libuv detects that the console has been resized. 984 SIGWINCH is emulated by libuv when the program uses a uv_tty_t handle to write 985 to the console. SIGWINCH may not always be delivered in a timely manner; libuv 986 will only detect size changes when the cursor is being moved. When a readable 987 [`uv_tty_t`][] handle is used in raw mode, resizing the console buffer will 988 also trigger a SIGWINCH signal. 989 - Watchers for other signals can be successfully created, but these signals 990 are never received. These signals are: SIGILL, SIGABRT, SIGFPE, SIGSEGV, 991 SIGTERM and SIGKILL. 992 - Calls to raise() or abort() to programmatically raise a signal are not 993 detected by libuv; these will not trigger a signal watcher. 994 995**Unix Notes:** 996 997 - SIGKILL and SIGSTOP are impossible to catch. 998 - Handling SIGBUS, SIGFPE, SIGILL or SIGSEGV via libuv results into undefined 999 behavior. 1000 - SIGABRT will not be caught by libuv if generated by abort(), e.g. through 1001 assert(). 1002 - On Linux SIGRT0 and SIGRT1 (signals 32 and 33) are used by the NPTL pthreads 1003 library to manage threads. Installing watchers for those signals will lead to 1004 unpredictable behavior and is strongly discouraged. Future versions of libuv 1005 may simply reject them. 1006 1007```lua 1008-- Create a new signal handler 1009local signal = uv.new_signal() 1010-- Define a handler function 1011uv.signal_start(signal, "sigint", function(signal) 1012 print("got " .. signal .. ", shutting down") 1013 os.exit(1) 1014end) 1015``` 1016 1017### `uv.new_signal()` 1018 1019Creates and initializes a new `uv_signal_t`. Returns the Lua userdata wrapping 1020it. 1021 1022**Returns:** `uv_signal_t userdata` or `fail` 1023 1024### `uv.signal_start(signal, signum, callback)` 1025 1026> method form `signal:start(signum, callback)` 1027 1028**Parameters:** 1029- `signal`: `uv_signal_t userdata` 1030- `signum`: `integer` or `string` 1031- `callback`: `callable` 1032 - `signum`: `string` 1033 1034Start the handle with the given callback, watching for the given signal. 1035 1036**Returns:** `0` or `fail` 1037 1038### `uv.signal_start_oneshot(signal, signum, callback)` 1039 1040> method form `signal:start_oneshot(signum, callback)` 1041 1042**Parameters:** 1043- `signal`: `uv_signal_t userdata` 1044- `signum`: `integer` or `string` 1045- `callback`: `callable` 1046 - `signum`: `string` 1047 1048Same functionality as `uv.signal_start()` but the signal handler is reset the moment the signal is received. 1049 1050**Returns:** `0` or `fail` 1051 1052### `uv.signal_stop(signal)` 1053 1054> method form `signal:stop()` 1055 1056**Parameters:** 1057- `signal`: `uv_signal_t userdata` 1058 1059Stop the handle, the callback will no longer be called. 1060 1061**Returns:** `0` or `fail` 1062 1063## `uv_process_t` — Process handle 1064 1065[`uv_process_t`]: #uv_process_t--process-handle 1066 1067> [`uv_handle_t`][] functions also apply. 1068 1069Process handles will spawn a new process and allow the user to control it and 1070establish communication channels with it using streams. 1071 1072### `uv.disable_stdio_inheritance()` 1073 1074Disables inheritance for file descriptors / handles that this process inherited 1075from its parent. The effect is that child processes spawned by this process 1076don't accidentally inherit these handles. 1077 1078It is recommended to call this function as early in your program as possible, 1079before the inherited file descriptors can be closed or duplicated. 1080 1081**Returns:** Nothing. 1082 1083**Note:** This function works on a best-effort basis: there is no guarantee that 1084libuv can discover all file descriptors that were inherited. In general it does 1085a better job on Windows than it does on Unix. 1086 1087### `uv.spawn(path, options, on_exit)` 1088 1089**Parameters:** 1090- `path`: `string` 1091- `options`: `table` (see below) 1092- `on_exit`: `callable` 1093 - `code`: `integer` 1094 - `signal`: `integer` 1095 1096Initializes the process handle and starts the process. If the process is 1097successfully spawned, this function will return the handle and pid of the child 1098process. 1099 1100Possible reasons for failing to spawn would include (but not be limited to) the 1101file to execute not existing, not having permissions to use the setuid or setgid 1102specified, or not having enough memory to allocate for the new process. 1103 1104```lua 1105local stdin = uv.new_pipe() 1106local stdout = uv.new_pipe() 1107local stderr = uv.new_pipe() 1108 1109print("stdin", stdin) 1110print("stdout", stdout) 1111print("stderr", stderr) 1112 1113local handle, pid = uv.spawn("cat", { 1114 stdio = {stdin, stdout, stderr} 1115}, function(code, signal) -- on exit 1116 print("exit code", code) 1117 print("exit signal", signal) 1118end) 1119 1120print("process opened", handle, pid) 1121 1122uv.read_start(stdout, function(err, data) 1123 assert(not err, err) 1124 if data then 1125 print("stdout chunk", stdout, data) 1126 else 1127 print("stdout end", stdout) 1128 end 1129end) 1130 1131uv.read_start(stderr, function(err, data) 1132 assert(not err, err) 1133 if data then 1134 print("stderr chunk", stderr, data) 1135 else 1136 print("stderr end", stderr) 1137 end 1138end) 1139 1140uv.write(stdin, "Hello World") 1141 1142uv.shutdown(stdin, function() 1143 print("stdin shutdown", stdin) 1144 uv.close(handle, function() 1145 print("process closed", handle, pid) 1146 end) 1147end) 1148``` 1149 1150The `options` table accepts the following fields: 1151 1152 - `options.args` - Command line arguments as a list of string. The first 1153 string should be the path to the program. On Windows, this uses CreateProcess 1154 which concatenates the arguments into a string. This can cause some strange 1155 errors. (See `options.verbatim` below for Windows.) 1156 - `options.stdio` - Set the file descriptors that will be made available to 1157 the child process. The convention is that the first entries are stdin, stdout, 1158 and stderr. (**Note**: On Windows, file descriptors after the third are 1159 available to the child process only if the child processes uses the MSVCRT 1160 runtime.) 1161 - `options.env` - Set environment variables for the new process. 1162 - `options.cwd` - Set the current working directory for the sub-process. 1163 - `options.uid` - Set the child process' user id. 1164 - `options.gid` - Set the child process' group id. 1165 - `options.verbatim` - If true, do not wrap any arguments in quotes, or 1166 perform any other escaping, when converting the argument list into a command 1167 line string. This option is only meaningful on Windows systems. On Unix it is 1168 silently ignored. 1169 - `options.detached` - If true, spawn the child process in a detached state - 1170 this will make it a process group leader, and will effectively enable the 1171 child to keep running after the parent exits. Note that the child process 1172 will still keep the parent's event loop alive unless the parent process calls 1173 `uv.unref()` on the child's process handle. 1174 - `options.hide` - If true, hide the subprocess console window that would 1175 normally be created. This option is only meaningful on Windows systems. On 1176 Unix it is silently ignored. 1177 1178The `options.stdio` entries can take many shapes. 1179 1180 - If they are numbers, then the child process inherits that same zero-indexed 1181 fd from the parent process. 1182 - If `uv_stream_t` handles are passed in, those are used as a read-write pipe 1183 or inherited stream depending if the stream has a valid fd. 1184 - Including `nil` placeholders means to ignore that fd in the child process. 1185 1186When the child process exits, `on_exit` is called with an exit code and signal. 1187 1188**Returns:** `uv_process_t userdata`, `integer` 1189 1190### `uv.process_kill(process, signum)` 1191 1192> method form `process:kill(signum)` 1193 1194**Parameters:** 1195- `process`: `uv_process_t userdata` 1196- `signum`: `integer` or `string` 1197 1198Sends the specified signal to the given process handle. Check the documentation 1199on `uv_signal_t` for signal support, specially on Windows. 1200 1201**Returns:** `0` or `fail` 1202 1203### `uv.kill(pid, signum)` 1204 1205**Parameters:** 1206- `pid`: `integer` 1207- `signum`: `integer` or `string` 1208 1209Sends the specified signal to the given PID. Check the documentation on 1210`uv_signal_t` for signal support, specially on Windows. 1211 1212**Returns:** `0` or `fail` 1213 1214### `uv.process_get_pid(process)` 1215 1216> method form `process:get_pid()` 1217 1218**Parameters:** 1219- `process`: `uv_process_t userdata` 1220 1221Returns the handle's pid. 1222 1223**Returns:** `integer` 1224 1225## `uv_stream_t` — Stream handle 1226 1227[`uv_stream_t`]: #uv_stream_t--stream-handle 1228 1229> [`uv_handle_t`][] functions also apply. 1230 1231Stream handles provide an abstraction of a duplex communication channel. 1232[`uv_stream_t`][] is an abstract type, libuv provides 3 stream implementations 1233in the form of [`uv_tcp_t`][], [`uv_pipe_t`][] and [`uv_tty_t`][]. 1234 1235### `uv.shutdown(stream, [callback])` 1236 1237> method form `stream:shutdown([callback])` 1238 1239**Parameters:** 1240- `stream`: `userdata` for sub-type of `uv_stream_t` 1241- `callback`: `callable` or `nil` 1242 - `err`: `nil` or `string` 1243 1244Shutdown the outgoing (write) side of a duplex stream. It waits for pending 1245write requests to complete. The callback is called after shutdown is complete. 1246 1247**Returns:** `uv_shutdown_t userdata` or `fail` 1248 1249### `uv.listen(stream, backlog, callback)` 1250 1251> method form `stream:listen(backlog, callback)` 1252 1253**Parameters:** 1254- `stream`: `userdata` for sub-type of `uv_stream_t` 1255- `backlog`: `integer` 1256- `callback`: `callable` 1257 - `err`: `nil` or `string` 1258 1259Start listening for incoming connections. `backlog` indicates the number of 1260connections the kernel might queue, same as `listen(2)`. When a new incoming 1261connection is received the callback is called. 1262 1263**Returns:** `0` or `fail` 1264 1265### `uv.accept(stream, client_stream)` 1266 1267> method form `stream:accept(client_stream)` 1268 1269**Parameters:** 1270- `stream`: `userdata` for sub-type of `uv_stream_t` 1271- `client_stream`: `userdata` for sub-type of `uv_stream_t` 1272 1273This call is used in conjunction with `uv.listen()` to accept incoming 1274connections. Call this function after receiving a callback to accept the 1275connection. 1276 1277When the connection callback is called it is guaranteed that this function 1278will complete successfully the first time. If you attempt to use it more than 1279once, it may fail. It is suggested to only call this function once per 1280connection call. 1281 1282**Returns:** `0` or `fail` 1283 1284```lua 1285server:listen(128, function (err) 1286 local client = uv.new_tcp() 1287 server:accept(client) 1288end) 1289``` 1290 1291### `uv.read_start(stream, callback)` 1292 1293> method form `stream:read_start(callback)` 1294 1295**Parameters:** 1296- `stream`: `userdata` for sub-type of `uv_stream_t` 1297- `callback`: `callable` 1298 - `err`: `nil` or `string` 1299 - `data`: `string` or `nil` 1300 1301Read data from an incoming stream. The callback will be made several times until 1302there is no more data to read or `uv.read_stop()` is called. When we've reached 1303EOF, `data` will be `nil`. 1304 1305**Returns:** `0` or `fail` 1306 1307```lua 1308stream:read_start(function (err, chunk) 1309 if err then 1310 -- handle read error 1311 elseif chunk then 1312 -- handle data 1313 else 1314 -- handle disconnect 1315 end 1316end) 1317``` 1318 1319### `uv.read_stop(stream)` 1320 1321> method form `stream:read_stop()` 1322 1323**Parameters:** 1324- `stream`: `userdata` for sub-type of `uv_stream_t` 1325 1326Stop reading data from the stream. The read callback will no longer be called. 1327 1328This function is idempotent and may be safely called on a stopped stream. 1329 1330**Returns:** `0` or `fail` 1331 1332### `uv.write(stream, data, [callback])` 1333 1334> method form `stream:write(data, [callback])` 1335 1336**Parameters:** 1337- `stream`: `userdata` for sub-type of `uv_stream_t` 1338- `data`: `buffer` 1339- `callback`: `callable` or `nil` 1340 - `err`: `nil` or `string` 1341 1342Write data to stream. 1343 1344`data` can either be a Lua string or a table of strings. If a table is passed 1345in, the C backend will use writev to send all strings in a single system call. 1346 1347The optional `callback` is for knowing when the write is complete. 1348 1349**Returns:** `uv_write_t userdata` or `fail` 1350 1351### `uv.write2(stream, data, send_handle, [callback])` 1352 1353> method form `stream:write2(data, send_handle, [callback])` 1354 1355**Parameters:** 1356- `stream`: `userdata` for sub-type of `uv_stream_t` 1357- `data`: `buffer` 1358- `send_handle`: `userdata` for sub-type of `uv_stream_t` 1359- `callback`: `callable` or `nil` 1360 - `err`: `nil` or `string` 1361 1362Extended write function for sending handles over a pipe. The pipe must be 1363initialized with `ipc` option `true`. 1364 1365**Returns:** `uv_write_t userdata` or `fail` 1366 1367**Note:** `send_handle` must be a TCP socket or pipe, which is a server or a 1368connection (listening or connected state). Bound sockets or pipes will be 1369assumed to be servers. 1370 1371### `uv.try_write(stream, data)` 1372 1373> method form `stream:try_write(data)` 1374 1375**Parameters:** 1376- `stream`: `userdata` for sub-type of `uv_stream_t` 1377- `data`: `buffer` 1378 1379Same as `uv.write()`, but won't queue a write request if it can't be completed 1380immediately. 1381 1382Will return number of bytes written (can be less than the supplied buffer size). 1383 1384**Returns:** `integer` or `fail` 1385 1386### `uv.is_readable(stream)` 1387 1388> method form `stream:is_readable()` 1389 1390**Parameters:** 1391- `stream`: `userdata` for sub-type of `uv_stream_t` 1392 1393Returns `true` if the stream is readable, `false` otherwise. 1394 1395**Returns:** `boolean` 1396 1397### `uv.is_writable(stream)` 1398 1399> method form `stream:is_writable()` 1400 1401**Parameters:** 1402- `stream`: `userdata` for sub-type of `uv_stream_t` 1403 1404Returns `true` if the stream is writable, `false` otherwise. 1405 1406**Returns:** `boolean` 1407 1408### `uv.stream_set_blocking(stream, blocking)` 1409 1410> method form `stream:set_blocking(blocking)` 1411 1412**Parameters:** 1413- `stream`: `userdata` for sub-type of `uv_stream_t` 1414- `blocking`: `boolean` 1415 1416Enable or disable blocking mode for a stream. 1417 1418When blocking mode is enabled all writes complete synchronously. The interface 1419remains unchanged otherwise, e.g. completion or failure of the operation will 1420still be reported through a callback which is made asynchronously. 1421 1422**Returns:** `0` or `fail` 1423 1424**Warning**: Relying too much on this API is not recommended. It is likely to 1425change significantly in the future. Currently this only works on Windows and 1426only for `uv_pipe_t` handles. Also libuv currently makes no ordering guarantee 1427when the blocking mode is changed after write requests have already been 1428submitted. Therefore it is recommended to set the blocking mode immediately 1429after opening or creating the stream. 1430 1431### `uv.stream_get_write_queue_size()` 1432 1433> method form `stream:get_write_queue_size()` 1434 1435Returns the stream's write queue size. 1436 1437**Returns:** `integer` 1438 1439## `uv_tcp_t` — TCP handle 1440 1441[`uv_tcp_t`]: #uv_tcp_t--tcp-handle 1442 1443> [`uv_handle_t`][] and [`uv_stream_t`][] functions also apply. 1444 1445TCP handles are used to represent both TCP streams and servers. 1446 1447### `uv.new_tcp([flags])` 1448 1449**Parameters:** 1450- `flags`: `string` or `nil` 1451 1452Creates and initializes a new `uv_tcp_t`. Returns the Lua userdata wrapping it. 1453Flags may be a family string: `"unix"`, `"inet"`, `"inet6"`, `"ipx"`, 1454`"netlink"`, `"x25"`, `"ax25"`, `"atmpvc"`, `"appletalk"`, or `"packet"`. 1455 1456**Returns:** `uv_tcp_t userdata` or `fail` 1457 1458### `uv.tcp_open(tcp, sock)` 1459 1460> method form `tcp:open(sock)` 1461 1462**Parameters:** 1463- `tcp`: `uv_tcp_t userdata` 1464- `sock`: `integer` 1465 1466Open an existing file descriptor or SOCKET as a TCP handle. 1467 1468**Returns:** `0` or `fail` 1469 1470**Note:** The passed file descriptor or SOCKET is not checked for its type, but it's required that it represents a valid stream socket. 1471 1472### `uv.tcp_nodelay(tcp, enable)` 1473 1474> method form `tcp:nodelay(enable)` 1475 1476**Parameters:** 1477- `tcp`: `uv_tcp_t userdata` 1478- `enable`: `boolean` 1479 1480Enable / disable Nagle's algorithm. 1481 1482**Returns:** `0` or `fail` 1483 1484### `uv.tcp_keepalive(tcp, enable, [delay])` 1485 1486> method form `tcp:keepalive(enable, [delay])` 1487 1488**Parameters:** 1489- `tcp`: `uv_tcp_t userdata` 1490- `enable`: `boolean` 1491- `delay`: `integer` or `nil` 1492 1493Enable / disable TCP keep-alive. `delay` is the initial delay in seconds, 1494ignored when enable is `false`. 1495 1496**Returns:** `0` or `fail` 1497 1498### `uv.tcp_simultaneous_accepts(tcp, enable)` 1499 1500> method form `tcp:simultaneous_accepts(enable)` 1501 1502**Parameters:** 1503- `tcp`: `uv_tcp_t userdata` 1504- `enable`: `boolean` 1505 1506Enable / disable simultaneous asynchronous accept requests that are queued by 1507the operating system when listening for new TCP connections. 1508 1509This setting is used to tune a TCP server for the desired performance. Having 1510simultaneous accepts can significantly improve the rate of accepting connections 1511(which is why it is enabled by default) but may lead to uneven load distribution 1512in multi-process setups. 1513 1514**Returns:** `0` or `fail` 1515 1516### `uv.tcp_bind(tcp, host, port, [flags])` 1517 1518> method form `tcp:bind(host, port, [flags])` 1519 1520**Parameters:** 1521- `tcp`: `uv_tcp_t userdata` 1522- `host`: `string` 1523- `port`: `integer` 1524- `flags`: `table` or `nil` 1525 - `ipv6only`: `boolean` 1526 1527Bind the handle to an host and port. `host` should be an IP address and 1528not a domain name. Any `flags` are set with a table with field `ipv6only` 1529equal to `true` or `false`. 1530 1531When the port is already taken, you can expect to see an `EADDRINUSE` error 1532from either `uv.tcp_bind()`, `uv.listen()` or `uv.tcp_connect()`. That is, a 1533successful call to this function does not guarantee that the call to `uv.listen()` 1534or `uv.tcp_connect()` will succeed as well. 1535 1536Use a port of `0` to let the OS assign an ephemeral port. You can look it up 1537later using `uv.tcp_getsockname()`. 1538 1539**Returns:** `0` or `fail` 1540 1541### `uv.tcp_getpeername(tcp)` 1542 1543> method form `tcp:getpeername()` 1544 1545**Parameters:** 1546- `tcp`: `uv_tcp_t userdata` 1547 1548Get the current address to which the handle is bound. 1549 1550**Returns:** `table` or `fail` 1551- `ip` : `string` 1552- `family` : `string` 1553- `port` : `integer` 1554 1555### `uv.tcp_getsockname(tcp)` 1556 1557> method form `tcp:getsockname()` 1558 1559**Parameters:** 1560- `tcp`: `uv_tcp_t userdata` 1561 1562Get the address of the peer connected to the handle. 1563 1564**Returns:** `table` or `fail` 1565- `ip` : `string` 1566- `family` : `string` 1567- `port` : `integer` 1568 1569### `uv.tcp_connect(tcp, host, port, callback)` 1570 1571> method form `tcp:connect(host, port, callback)` 1572 1573**Parameters:** 1574- `tcp`: `uv_tcp_t userdata` 1575- `host`: `string` 1576- `port`: `integer` 1577- `callback`: `callable` 1578 - `err`: `nil` or `string` 1579 1580Establish an IPv4 or IPv6 TCP connection. 1581 1582**Returns:** `uv_connect_t userdata` or `fail` 1583 1584```lua 1585local client = uv.new_tcp() 1586client:connect("127.0.0.1", 8080, function (err) 1587 -- check error and carry on. 1588end) 1589``` 1590 1591### `uv.tcp_write_queue_size(tcp)` 1592 1593> method form `tcp:write_queue_size()` 1594 1595**Deprecated:** Please use `uv.stream_get_write_queue_size()` instead. 1596 1597### `uv.tcp_close_reset([callback])` 1598 1599> method form `tcp:close_reset([callback])` 1600 1601**Parameters:** 1602- `tcp`: `uv_tcp_t userdata` 1603- `callback`: `callable` or `nil` 1604 1605Resets a TCP connection by sending a RST packet. This is accomplished by setting 1606the SO_LINGER socket option with a linger interval of zero and then calling 1607`uv.close()`. Due to some platform inconsistencies, mixing of `uv.shutdown()` 1608and `uv.tcp_close_reset()` calls is not allowed. 1609 1610**Returns:** `0` or `fail` 1611 1612### `uv.socketpair([socktype], [protocol], [flags1], [flags2])` 1613 1614**Parameters:** 1615- `socktype`: `string`, `integer` or `nil` (default: `stream`) 1616- `protocol`: `string`, `integer` or `nil` (default: 0) 1617- `flags1`: `table` or `nil` 1618 - `nonblock`: `boolean` (default: `false`) 1619- `flags2`: `table` or `nil` 1620 - `nonblock`: `boolean` (default: `false`) 1621 1622Create a pair of connected sockets with the specified properties. The resulting handles can be passed to `uv.tcp_open`, used with `uv.spawn`, or for any other purpose. 1623 1624When specified as a string, `socktype` must be one of `"stream"`, `"dgram"`, `"raw"`, 1625`"rdm"`, or `"seqpacket"`. 1626 1627When `protocol` is set to 0 or nil, it will be automatically chosen based on the socket's domain and type. When `protocol` is specified as a string, it will be looked up using the `getprotobyname(3)` function (examples: `"ip"`, `"icmp"`, `"tcp"`, `"udp"`, etc). 1628 1629Flags: 1630 - `nonblock`: Opens the specified socket handle for `OVERLAPPED` or `FIONBIO`/`O_NONBLOCK` I/O usage. This is recommended for handles that will be used by libuv, and not usually recommended otherwise. 1631 1632Equivalent to `socketpair(2)` with a domain of `AF_UNIX`. 1633 1634**Returns:** `table` or `fail` 1635- `[1, 2]` : `integer` (file descriptor) 1636 1637```lua 1638-- Simple read/write with tcp 1639local fds = uv.socketpair(nil, nil, {nonblock=true}, {nonblock=true}) 1640 1641local sock1 = uv.new_tcp() 1642sock1:open(fds[1]) 1643 1644local sock2 = uv.new_tcp() 1645sock2:open(fds[2]) 1646 1647sock1:write("hello") 1648sock2:read_start(function(err, chunk) 1649 assert(not err, err) 1650 print(chunk) 1651end) 1652``` 1653 1654## `uv_pipe_t` — Pipe handle 1655 1656[`uv_pipe_t`]: #uv_pipe_t--pipe-handle 1657 1658> [`uv_handle_t`][] and [`uv_stream_t`][] functions also apply. 1659 1660Pipe handles provide an abstraction over local domain sockets on Unix and named pipes on Windows. 1661 1662```lua 1663local pipe = uv.new_pipe(false) 1664 1665pipe:bind('/tmp/sock.test') 1666 1667pipe:listen(128, function() 1668 local client = uv.new_pipe(false) 1669 pipe:accept(client) 1670 client:write("hello!\n") 1671 client:close() 1672end) 1673``` 1674 1675### `uv.new_pipe([ipc])` 1676 1677**Parameters:** 1678- `ipc`: `boolean` or `nil` (default: `false`) 1679 1680Creates and initializes a new `uv_pipe_t`. Returns the Lua userdata wrapping 1681it. The `ipc` argument is a boolean to indicate if this pipe will be used for 1682handle passing between processes. 1683 1684**Returns:** `uv_pipe_t userdata` or `fail` 1685 1686### `uv.pipe_open(pipe, fd)` 1687 1688> method form `pipe:open(fd)` 1689 1690**Parameters:** 1691- `pipe`: `uv_pipe_t userdata` 1692- `fd`: `integer` 1693 1694Open an existing file descriptor or [`uv_handle_t`][] as a pipe. 1695 1696**Returns:** `0` or `fail` 1697 1698**Note**: The file descriptor is set to non-blocking mode. 1699 1700### `uv.pipe_bind(pipe, name)` 1701 1702> method form `pipe:bind(name)` 1703 1704**Parameters:** 1705- `pipe`: `uv_pipe_t userdata` 1706- `name`: `string` 1707 1708Bind the pipe to a file path (Unix) or a name (Windows). 1709 1710**Returns:** `0` or `fail` 1711 1712**Note**: Paths on Unix get truncated to sizeof(sockaddr_un.sun_path) bytes, 1713typically between 92 and 108 bytes. 1714 1715### `uv.pipe_connect(pipe, name, [callback])` 1716 1717> method form `pipe:connect(name, [callback])` 1718 1719**Parameters:** 1720- `pipe`: `uv_pipe_t userdata` 1721- `name`: `string` 1722- `callback`: `callable` or `nil` 1723 - `err`: `nil` or `string` 1724 1725Connect to the Unix domain socket or the named pipe. 1726 1727**Returns:** `uv_connect_t userdata` or `fail` 1728 1729**Note**: Paths on Unix get truncated to sizeof(sockaddr_un.sun_path) bytes, 1730typically between 92 and 108 bytes. 1731 1732### `uv.pipe_getsockname(pipe)` 1733 1734> method form `pipe:getsockname()` 1735 1736**Parameters:** 1737- `pipe`: `uv_pipe_t userdata` 1738 1739Get the name of the Unix domain socket or the named pipe. 1740 1741**Returns:** `string` or `fail` 1742 1743### `uv.pipe_getpeername(pipe)` 1744 1745> method form `pipe:getpeername()` 1746 1747**Parameters:** 1748- `pipe`: `uv_pipe_t userdata` 1749 1750Get the name of the Unix domain socket or the named pipe to which the handle is 1751connected. 1752 1753**Returns:** `string` or `fail` 1754 1755### `uv.pipe_pending_instances(pipe, count)` 1756 1757> method form `pipe:pending_instances(count)` 1758 1759**Parameters:** 1760- `pipe`: `uv_pipe_t userdata` 1761- `count`: `integer` 1762 1763Set the number of pending pipe instance handles when the pipe server is waiting 1764for connections. 1765 1766**Returns:** Nothing. 1767 1768**Note**: This setting applies to Windows only. 1769 1770### `uv.pipe_pending_count(pipe)` 1771 1772> method form `pipe:pending_count()` 1773 1774**Parameters:** 1775- `pipe`: `uv_pipe_t userdata` 1776 1777Returns the pending pipe count for the named pipe. 1778 1779**Returns:** `integer` 1780 1781### `uv.pipe_pending_type(pipe)` 1782 1783> method form `pipe:pending_type()` 1784 1785**Parameters:** 1786- `pipe`: `uv_pipe_t userdata` 1787 1788Used to receive handles over IPC pipes. 1789 1790First - call `uv.pipe_pending_count()`, if it's > 0 then initialize a handle of 1791the given type, returned by `uv.pipe_pending_type()` and call 1792`uv.accept(pipe, handle)`. 1793 1794**Returns:** `string` 1795 1796### `uv.pipe_chmod(pipe, flags)` 1797 1798> method form `pipe:chmod(flags)` 1799 1800**Parameters:** 1801- `pipe`: `uv_pipe_t userdata` 1802- `flags`: `string` 1803 1804Alters pipe permissions, allowing it to be accessed from processes run by different users. 1805Makes the pipe writable or readable by all users. `flags` are: `"r"`, `"w"`, `"rw"`, or `"wr"` 1806where `r` is `READABLE` and `w` is `WRITABLE`. This function is blocking. 1807 1808**Returns:** `0` or `fail` 1809 1810### `uv.pipe(read_flags, write_flags)` 1811 1812**Parameters:** 1813- `read_flags`: `table` or `nil` 1814 - `nonblock`: `boolean` (default: `false`) 1815- `write_flags`: `table` or `nil` 1816 - `nonblock`: `boolean` (default: `false`) 1817 1818Create a pair of connected pipe handles. Data may be written to the `write` fd and read from the `read` fd. The resulting handles can be passed to `pipe_open`, used with `spawn`, or for any other purpose. 1819 1820Flags: 1821 - `nonblock`: Opens the specified socket handle for `OVERLAPPED` or `FIONBIO`/`O_NONBLOCK` I/O usage. This is recommended for handles that will be used by libuv, and not usually recommended otherwise. 1822 1823Equivalent to `pipe(2)` with the `O_CLOEXEC` flag set. 1824 1825**Returns:** `table` or `fail` 1826- `read` : `integer` (file descriptor) 1827- `write` : `integer` (file descriptor) 1828 1829```lua 1830-- Simple read/write with pipe_open 1831local fds = uv.pipe({nonblock=true}, {nonblock=true}) 1832 1833local read_pipe = uv.new_pipe() 1834read_pipe:open(fds.read) 1835 1836local write_pipe = uv.new_pipe() 1837write_pipe:open(fds.write) 1838 1839write_pipe:write("hello") 1840read_pipe:read_start(function(err, chunk) 1841 assert(not err, err) 1842 print(chunk) 1843end) 1844``` 1845 1846## `uv_tty_t` — TTY handle 1847 1848[`uv_tty_t`]: #uv_tty_t--tty-handle 1849 1850> [`uv_handle_t`][] and [`uv_stream_t`][] functions also apply. 1851 1852TTY handles represent a stream for the console. 1853 1854```lua 1855-- Simple echo program 1856local stdin = uv.new_tty(0, true) 1857local stdout = uv.new_tty(1, false) 1858 1859stdin:read_start(function (err, data) 1860 assert(not err, err) 1861 if data then 1862 stdout:write(data) 1863 else 1864 stdin:close() 1865 stdout:close() 1866 end 1867end) 1868``` 1869 1870### `uv.new_tty(fd, readable)` 1871 1872**Parameters:** 1873- `fd`: `integer` 1874- `readable`: `boolean` 1875 1876Initialize a new TTY stream with the given file descriptor. Usually the file 1877descriptor will be: 1878 1879 - 0 - stdin 1880 - 1 - stdout 1881 - 2 - stderr 1882 1883On Unix this function will determine the path of the fd of the terminal using 1884ttyname_r(3), open it, and use it if the passed file descriptor refers to a TTY. 1885This lets libuv put the tty in non-blocking mode without affecting other 1886processes that share the tty. 1887 1888This function is not thread safe on systems that don’t support ioctl TIOCGPTN or TIOCPTYGNAME, for instance OpenBSD and Solaris. 1889 1890**Returns:** `uv_tty_t userdata` or `fail` 1891 1892**Note:** If reopening the TTY fails, libuv falls back to blocking writes. 1893 1894### `uv.tty_set_mode(tty, mode)` 1895 1896> method form `tty:set_mode(mode)` 1897 1898**Parameters:** 1899- `tty`: `uv_tty_t userdata` 1900- `mode`: `integer` 1901 1902Set the TTY using the specified terminal mode. 1903 1904Parameter `mode` is a C enum with the following values: 1905 1906 - 0 - UV_TTY_MODE_NORMAL: Initial/normal terminal mode 1907 - 1 - UV_TTY_MODE_RAW: Raw input mode (On Windows, ENABLE_WINDOW_INPUT is 1908 also enabled) 1909 - 2 - UV_TTY_MODE_IO: Binary-safe I/O mode for IPC (Unix-only) 1910 1911**Returns:** `0` or `fail` 1912 1913### `uv.tty_reset_mode()` 1914 1915To be called when the program exits. Resets TTY settings to default values for 1916the next process to take over. 1917 1918This function is async signal-safe on Unix platforms but can fail with error 1919code `EBUSY` if you call it when execution is inside `uv.tty_set_mode()`. 1920 1921**Returns:** `0` or `fail` 1922 1923### `uv.tty_get_winsize(tty)` 1924 1925> method form `tty:get_winsize()` 1926 1927**Parameters:** 1928- `tty`: `uv_tty_t userdata` 1929 1930Gets the current Window width and height. 1931 1932**Returns:** `integer, integer` or `fail` 1933 1934### `uv.tty_set_vterm_state(state)` 1935 1936**Parameters:** 1937- `state`: `string` 1938 1939Controls whether console virtual terminal sequences are processed by libuv or 1940console. Useful in particular for enabling ConEmu support of ANSI X3.64 and 1941Xterm 256 colors. Otherwise Windows10 consoles are usually detected 1942automatically. State may be a family string: `"supported"` or `"unsupported"`. 1943 1944This function is only meaningful on Windows systems. On Unix it is silently 1945ignored. 1946 1947**Returns:** none 1948 1949### `uv.tty_get_vterm_state()` 1950 1951Get the current state of whether console virtual terminal sequences are handled 1952by libuv or the console. The return value is `"supported"` or `"unsupported"`. 1953 1954This function is not implemented on Unix, where it returns `ENOTSUP`. 1955 1956**Returns:** `string` or `fail` 1957 1958## `uv_udp_t` — UDP handle 1959 1960[`uv_udp_t`]: #uv_udp_t--udp-handle 1961 1962> [`uv_handle_t`][] functions also apply. 1963 1964UDP handles encapsulate UDP communication for both clients and servers. 1965 1966### `uv.new_udp([flags])` 1967 1968**Parameters:** 1969- `flags`: `table` or `nil` 1970 - `family`: `string` or `nil` 1971 - `mmsgs`: `integer` or `nil` (default: `1`) 1972 1973Creates and initializes a new `uv_udp_t`. Returns the Lua userdata wrapping 1974it. The actual socket is created lazily. 1975 1976When specified, `family` must be one of `"unix"`, `"inet"`, `"inet6"`, 1977`"ipx"`, `"netlink"`, `"x25"`, `"ax25"`, `"atmpvc"`, `"appletalk"`, or 1978`"packet"`. 1979 1980When specified, `mmsgs` determines the number of messages able to be received 1981at one time via `recvmmsg(2)` (the allocated buffer will be sized to be able 1982to fit the specified number of max size dgrams). Only has an effect on 1983platforms that support `recvmmsg(2)`. 1984 1985**Note:** For backwards compatibility reasons, `flags` can also be a string or 1986integer. When it is a string, it will be treated like the `family` key above. 1987When it is an integer, it will be used directly as the `flags` parameter when 1988calling `uv_udp_init_ex`. 1989 1990**Returns:** `uv_udp_t userdata` or `fail` 1991 1992### `uv.udp_get_send_queue_size()` 1993 1994> method form `udp:get_send_queue_size()` 1995 1996Returns the handle's send queue size. 1997 1998**Returns:** `integer` 1999 2000### `uv.udp_get_send_queue_count()` 2001 2002> method form `udp:get_send_count_size()` 2003 2004Returns the handle's send queue count. 2005 2006**Returns:** `integer` 2007 2008### `uv.udp_open(udp, fd)` 2009 2010> method form `udp:open(fd)` 2011 2012**Parameters:** 2013- `udp`: `uv_udp_t userdata` 2014- `fd`: `integer` 2015 2016Opens an existing file descriptor or Windows SOCKET as a UDP handle. 2017 2018Unix only: The only requirement of the sock argument is that it follows the 2019datagram contract (works in unconnected mode, supports sendmsg()/recvmsg(), 2020etc). In other words, other datagram-type sockets like raw sockets or netlink 2021sockets can also be passed to this function. 2022 2023The file descriptor is set to non-blocking mode. 2024 2025Note: The passed file descriptor or SOCKET is not checked for its type, but 2026it's required that it represents a valid datagram socket. 2027 2028**Returns:** `0` or `fail` 2029 2030### `uv.udp_bind(udp, host, port, [flags])` 2031 2032> method form `udp:bind(host, port, [flags])` 2033 2034**Parameters:** 2035- `udp`: `uv_udp_t userdata` 2036- `host`: `string` 2037- `port`: `number` 2038- `flags`: `table` or `nil` 2039 - `ipv6only`: `boolean` 2040 - `reuseaddr`: `boolean` 2041 2042Bind the UDP handle to an IP address and port. Any `flags` are set with a table 2043with fields `reuseaddr` or `ipv6only` equal to `true` or `false`. 2044 2045**Returns:** `0` or `fail` 2046 2047### `uv.udp_getsockname(udp)` 2048 2049> method form `udp:getsockname()` 2050 2051**Parameters:** 2052- `udp`: `uv_udp_t userdata` 2053 2054Get the local IP and port of the UDP handle. 2055 2056**Returns:** `table` or `fail` 2057- `ip` : `string` 2058- `family` : `string` 2059- `port` : `integer` 2060 2061### `uv.udp_getpeername(udp)` 2062 2063> method form `udp:getpeername()` 2064 2065**Parameters:** 2066- `udp`: `uv_udp_t userdata` 2067 2068Get the remote IP and port of the UDP handle on connected UDP handles. 2069 2070**Returns:** `table` or `fail` 2071- `ip` : `string` 2072- `family` : `string` 2073- `port` : `integer` 2074 2075### `uv.udp_set_membership(udp, multicast_addr, interface_addr, membership)` 2076 2077> method form `udp:set_membership(multicast_addr, interface_addr, membership)` 2078 2079**Parameters:** 2080- `udp`: `uv_udp_t userdata` 2081- `multicast_addr`: `string` 2082- `interface_addr`: `string` or `nil` 2083- `membership`: `string` 2084 2085Set membership for a multicast address. `multicast_addr` is multicast address to 2086set membership for. `interface_addr` is interface address. `membership` can be 2087the string `"leave"` or `"join"`. 2088 2089**Returns:** `0` or `fail` 2090 2091### `uv.udp_set_source_membership(udp, multicast_addr, interface_addr, source_addr, membership)` 2092 2093> method form `udp:set_source_membership(multicast_addr, interface_addr, source_addr, membership)` 2094 2095**Parameters:** 2096- `udp`: `uv_udp_t userdata` 2097- `multicast_addr`: `string` 2098- `interface_addr`: `string` or `nil` 2099- `source_addr`: `string` 2100- `membership`: `string` 2101 2102Set membership for a source-specific multicast group. `multicast_addr` is multicast 2103address to set membership for. `interface_addr` is interface address. `source_addr` 2104is source address. `membership` can be the string `"leave"` or `"join"`. 2105 2106**Returns:** `0` or `fail` 2107 2108### `uv.udp_set_multicast_loop(udp, on)` 2109 2110> method form `udp:set_multicast_loop(on)` 2111 2112**Parameters:** 2113- `udp`: `uv_udp_t userdata` 2114- `on`: `boolean` 2115 2116Set IP multicast loop flag. Makes multicast packets loop back to local 2117sockets. 2118 2119**Returns:** `0` or `fail` 2120 2121### `uv.udp_set_multicast_ttl(udp, ttl)` 2122 2123> method form `udp:set_multicast_ttl(ttl)` 2124 2125**Parameters:** 2126- `udp`: `uv_udp_t userdata` 2127- `ttl`: `integer` 2128 2129Set the multicast ttl. 2130 2131`ttl` is an integer 1 through 255. 2132 2133**Returns:** `0` or `fail` 2134 2135### `uv.udp_set_multicast_interface(udp, interface_addr)` 2136 2137> method form `udp:set_multicast_interface(interface_addr)` 2138 2139**Parameters:** 2140- `udp`: `uv_udp_t userdata` 2141- `interface_addr`: `string` 2142 2143Set the multicast interface to send or receive data on. 2144 2145**Returns:** `0` or `fail` 2146 2147### `uv.udp_set_broadcast(udp, on)` 2148 2149> method form `udp:set_broadcast(on)` 2150 2151**Parameters:** 2152- `udp`: `uv_udp_t userdata` 2153- `on`: `boolean` 2154 2155Set broadcast on or off. 2156 2157**Returns:** `0` or `fail` 2158 2159### `uv.udp_set_ttl(udp, ttl)` 2160 2161> method form `udp:set_ttl(ttl)` 2162 2163**Parameters:** 2164- `udp`: `uv_udp_t userdata` 2165- `ttl`: `integer` 2166 2167Set the time to live. 2168 2169`ttl` is an integer 1 through 255. 2170 2171**Returns:** `0` or `fail` 2172 2173### `uv.udp_send(udp, data, host, port, callback)` 2174 2175> method form `udp:send(data, host, port, callback)` 2176 2177**Parameters:** 2178- `udp`: `uv_udp_t userdata` 2179- `data`: `buffer` 2180- `host`: `string` 2181- `port`: `integer` 2182- `callback`: `callable` 2183 - `err`: `nil` or `string` 2184 2185Send data over the UDP socket. If the socket has not previously been bound 2186with `uv.udp_bind()` it will be bound to `0.0.0.0` (the "all interfaces" IPv4 2187address) and a random port number. 2188 2189**Returns:** `uv_udp_send_t userdata` or `fail` 2190 2191### `uv.udp_try_send(udp, data, host, port)` 2192 2193> method form `udp:try_send(data, host, port)` 2194 2195**Parameters:** 2196- `udp`: `uv_udp_t userdata` 2197- `data`: `buffer` 2198- `host`: `string` 2199- `port`: `integer` 2200 2201Same as `uv.udp_send()`, but won't queue a send request if it can't be 2202completed immediately. 2203 2204**Returns:** `integer` or `fail` 2205 2206### `uv.udp_recv_start(udp, callback)` 2207 2208> method form `udp:recv_start(callback)` 2209 2210**Parameters:** 2211- `udp`: `uv_udp_t userdata` 2212- `callback`: `callable` 2213 - `err`: `nil` or `string` 2214 - `data`: `string` or `nil` 2215 - `addr`: `table` or `nil` 2216 - `ip`: `string` 2217 - `port`: `integer` 2218 - `family`: `string` 2219 - `flags`: `table` 2220 - `partial`: `boolean` or `nil` 2221 - `mmsg_chunk`: `boolean` or `nil` 2222 2223Prepare for receiving data. If the socket has not previously been bound with 2224`uv.udp_bind()` it is bound to `0.0.0.0` (the "all interfaces" IPv4 address) 2225and a random port number. 2226 2227**Returns:** `0` or `fail` 2228 2229### `uv.udp_recv_stop(udp)` 2230 2231> method form `udp:recv_stop()` 2232 2233**Parameters:** 2234- `udp`: `uv_udp_t userdata` 2235 2236Stop listening for incoming datagrams. 2237 2238**Returns:** `0` or `fail` 2239 2240### `uv.udp_connect(udp, host, port)` 2241 2242> method form `udp:connect(host, port)` 2243 2244**Parameters:** 2245- `udp`: `uv_udp_t userdata` 2246- `host`: `string` 2247- `port`: `integer` 2248 2249Associate the UDP handle to a remote address and port, so every message sent by 2250this handle is automatically sent to that destination. Calling this function 2251with a NULL addr disconnects the handle. Trying to call `uv.udp_connect()` on an 2252already connected handle will result in an `EISCONN` error. Trying to disconnect 2253a handle that is not connected will return an `ENOTCONN` error. 2254 2255**Returns:** `0` or `fail` 2256 2257## `uv_fs_event_t` — FS Event handle 2258 2259[`uv_fs_event_t`]: #uv_fs_event_t--fs-event-handle 2260 2261> [`uv_handle_t`][] functions also apply. 2262 2263FS Event handles allow the user to monitor a given path for changes, for 2264example, if the file was renamed or there was a generic change in it. This 2265handle uses the best backend for the job on each platform. 2266 2267### `uv.new_fs_event()` 2268 2269Creates and initializes a new `uv_fs_event_t`. Returns the Lua userdata wrapping 2270it. 2271 2272**Returns:** `uv_fs_event_t userdata` or `fail` 2273 2274### `uv.fs_event_start(fs_event, path, flags, callback)` 2275 2276> method form `fs_event:start(path, flags, callback)` 2277 2278**Parameters:** 2279- `fs_event`: `uv_fs_event_t userdata` 2280- `path`: `string` 2281- `flags`: `table` 2282 - `watch_entry`: `boolean` or `nil` (default: `false`) 2283 - `stat`: `boolean` or `nil` (default: `false`) 2284 - `recursive`: `boolean` or `nil` (default: `false`) 2285- `callback`: `callable` 2286 - `err`: `nil` or `string` 2287 - `filename`: `string` 2288 - `events`: `table` 2289 - `change`: `boolean` or `nil` 2290 - `rename`: `boolean` or `nil` 2291 2292Start the handle with the given callback, which will watch the specified path 2293for changes. 2294 2295**Returns:** `0` or `fail` 2296 2297### `uv.fs_event_stop()` 2298 2299> method form `fs_event:stop()` 2300 2301Stop the handle, the callback will no longer be called. 2302 2303**Returns:** `0` or `fail` 2304 2305### `uv.fs_event_getpath()` 2306 2307> method form `fs_event:getpath()` 2308 2309Get the path being monitored by the handle. 2310 2311**Returns:** `string` or `fail` 2312 2313## `uv_fs_poll_t` — FS Poll handle 2314 2315[`uv_fs_poll_t`]: #uv_fs_poll_t--fs-poll-handle 2316 2317> [`uv_handle_t`][] functions also apply. 2318 2319FS Poll handles allow the user to monitor a given path for changes. Unlike 2320`uv_fs_event_t`, fs poll handles use `stat` to detect when a file has changed so 2321they can work on file systems where fs event handles can't. 2322 2323### `uv.new_fs_poll()` 2324 2325Creates and initializes a new `uv_fs_poll_t`. Returns the Lua userdata wrapping 2326it. 2327 2328**Returns:** `uv_fs_poll_t userdata` or `fail` 2329 2330### `uv.fs_poll_start(fs_poll, path, interval, callback)` 2331 2332> method form `fs_poll:start(path, interval, callback)` 2333 2334**Parameters:** 2335- `fs_event`: `uv_fs_event_t userdata` 2336- `path`: `string` 2337- `interval`: `integer` 2338- `callback`: `callable` 2339 - `err`: `nil` or `string` 2340 - `prev`: `table` or `nil` (see `uv.fs_stat`) 2341 - `curr`: `table` or `nil` (see `uv.fs_stat`) 2342 2343Check the file at `path` for changes every `interval` milliseconds. 2344 2345**Note:** For maximum portability, use multi-second intervals. Sub-second 2346intervals will not detect all changes on many file systems. 2347 2348**Returns:** `0` or `fail` 2349 2350### `uv.fs_poll_stop()` 2351 2352> method form `fs_poll:stop()` 2353 2354Stop the handle, the callback will no longer be called. 2355 2356**Returns:** `0` or `fail` 2357 2358### `uv.fs_poll_getpath()` 2359 2360> method form `fs_poll:getpath()` 2361 2362Get the path being monitored by the handle. 2363 2364**Returns:** `string` or `fail` 2365 2366## File system operations 2367 2368[File system operations]: #file-system-operations 2369 2370Most file system functions can operate synchronously or asynchronously. When a synchronous version is called (by omitting a callback), the function will 2371immediately return the results of the FS call. When an asynchronous version is 2372called (by providing a callback), the function will immediately return a 2373`uv_fs_t userdata` and asynchronously execute its callback; if an error is encountered, the first and only argument passed to the callback will be the `err` error string; if the operation completes successfully, the first argument will be `nil` and the remaining arguments will be the results of the FS call. 2374 2375Synchronous and asynchronous versions of `readFile` (with naive error handling) 2376are implemented below as an example: 2377 2378```lua 2379local function readFileSync(path) 2380 local fd = assert(uv.fs_open(path, "r", 438)) 2381 local stat = assert(uv.fs_fstat(fd)) 2382 local data = assert(uv.fs_read(fd, stat.size, 0)) 2383 assert(uv.fs_close(fd)) 2384 return data 2385end 2386 2387local data = readFileSync("main.lua") 2388print("synchronous read", data) 2389``` 2390 2391```lua 2392local function readFile(path, callback) 2393 uv.fs_open(path, "r", 438, function(err, fd) 2394 assert(not err, err) 2395 uv.fs_fstat(fd, function(err, stat) 2396 assert(not err, err) 2397 uv.fs_read(fd, stat.size, 0, function(err, data) 2398 assert(not err, err) 2399 uv.fs_close(fd, function(err) 2400 assert(not err, err) 2401 return callback(data) 2402 end) 2403 end) 2404 end) 2405 end) 2406end 2407 2408readFile("main.lua", function(data) 2409 print("asynchronous read", data) 2410end) 2411``` 2412 2413### `uv.fs_close(fd, [callback])` 2414 2415**Parameters:** 2416- `fd`: `integer` 2417- `callback`: `callable` (async version) or `nil` (sync version) 2418 - `err`: `nil` or `string` 2419 - `success`: `boolean` or `nil` 2420 2421Equivalent to `close(2)`. 2422 2423**Returns (sync version):** `boolean` or `fail` 2424 2425**Returns (async version):** `uv_fs_t userdata` 2426 2427### `uv.fs_open(path, flags, mode, [callback])` 2428 2429**Parameters:** 2430- `path`: `string` 2431- `flags`: `string` or `integer` 2432- `mode`: `integer` 2433- `callback`: `callable` (async version) or `nil` (sync version) 2434 - `err`: `nil` or `string` 2435 - `fd`: `integer` or `nil` 2436 2437Equivalent to `open(2)`. Access `flags` may be an integer or one of: `"r"`, 2438`"rs"`, `"sr"`, `"r+"`, `"rs+"`, `"sr+"`, `"w"`, `"wx"`, `"xw"`, `"w+"`, 2439`"wx+"`, `"xw+"`, `"a"`, `"ax"`, `"xa"`, `"a+"`, `"ax+"`, or "`xa+`". 2440 2441**Returns (sync version):** `integer` or `fail` 2442 2443**Returns (async version):** `uv_fs_t userdata` 2444 2445**Note:** On Windows, libuv uses `CreateFileW` and thus the file is always 2446opened in binary mode. Because of this, the `O_BINARY` and `O_TEXT` flags are 2447not supported. 2448 2449### `uv.fs_read(fd, size, [offset], [callback])` 2450 2451**Parameters:** 2452- `fd`: `integer` 2453- `size`: `integer` 2454- `offset`: `integer` or `nil` 2455- `callback`: `callable` (async version) or `nil` (sync version) 2456 - `err`: `nil` or `string` 2457 - `data`: `string` or `nil` 2458 2459Equivalent to `preadv(2)`. Returns any data. An empty string indicates EOF. 2460 2461If `offset` is nil or omitted, it will default to `-1`, which indicates 'use and update the current file offset.' 2462 2463**Note:** When `offset` is >= 0, the current file offset will not be updated by the read. 2464 2465**Returns (sync version):** `string` or `fail` 2466 2467**Returns (async version):** `uv_fs_t userdata` 2468 2469### `uv.fs_unlink(path, [callback])` 2470 2471**Parameters:** 2472- `path`: `string` 2473- `callback`: `callable` (async version) or `nil` (sync version) 2474 - `err`: `nil` or `string` 2475 - `success`: `boolean` or `nil` 2476 2477Equivalent to `unlink(2)`. 2478 2479**Returns (sync version):** `boolean` or `fail` 2480 2481**Returns (async version):** `uv_fs_t userdata` 2482 2483### `uv.fs_write(fd, data, [offset], [callback])` 2484 2485**Parameters:** 2486- `fd`: `integer` 2487- `data`: `buffer` 2488- `offset`: `integer` or `nil` 2489- `callback`: `callable` (async version) or `nil` (sync version) 2490 - `err`: `nil` or `string` 2491 - `bytes`: `integer` or `nil` 2492 2493Equivalent to `pwritev(2)`. Returns the number of bytes written. 2494 2495If `offset` is nil or omitted, it will default to `-1`, which indicates 'use and update the current file offset.' 2496 2497**Note:** When `offset` is >= 0, the current file offset will not be updated by the write. 2498 2499**Returns (sync version):** `integer` or `fail` 2500 2501**Returns (async version):** `uv_fs_t userdata` 2502 2503### `uv.fs_mkdir(path, mode, [callback])` 2504 2505**Parameters:** 2506- `path`: `string` 2507- `mode`: `integer` 2508- `callback`: `callable` (async version) or `nil` (sync version) 2509 - `err`: `nil` or `string` 2510 - `success`: `boolean` or `nil` 2511 2512Equivalent to `mkdir(2)`. 2513 2514**Returns (sync version):** `boolean` or `fail` 2515 2516**Returns (async version):** `uv_fs_t userdata` 2517 2518### `uv.fs_mkdtemp(template, [callback])` 2519 2520**Parameters:** 2521- `template`: `string` 2522- `callback`: `callable` (async version) or `nil` (sync version) 2523 - `err`: `nil` or `string` 2524 - `path`: `string` or `nil` 2525 2526Equivalent to `mkdtemp(3)`. 2527 2528**Returns (sync version):** `string` or `fail` 2529 2530**Returns (async version):** `uv_fs_t userdata` 2531 2532### `uv.fs_mkstemp(template, [callback])` 2533 2534**Parameters:** 2535- `template`: `string` 2536- `callback`: `callable` (async version) or `nil` (sync version) 2537 - `err`: `nil` or `string` 2538 - `fd`: `integer` or `nil` 2539 - `path`: `string` or `nil` 2540 2541Equivalent to `mkstemp(3)`. Returns a temporary file handle and filename. 2542 2543**Returns (sync version):** `integer, string` or `fail` 2544 2545**Returns (async version):** `uv_fs_t userdata` 2546 2547### `uv.fs_rmdir(path, [callback])` 2548 2549**Parameters:** 2550- `path`: `string` 2551- `callback`: `callable` (async version) or `nil` (sync version) 2552 - `err`: `nil` or `string` 2553 - `success`: `boolean` or `nil` 2554 2555Equivalent to `rmdir(2)`. 2556 2557**Returns (sync version):** `boolean` or `fail` 2558 2559**Returns (async version):** `uv_fs_t userdata` 2560 2561### `uv.fs_scandir(path, [callback])` 2562 2563**Parameters:** 2564- `path`: `string` 2565- `callback`: `callable` 2566 - `err`: `nil` or `string` 2567 - `success`: `uv_fs_t userdata` or `nil` 2568 2569Equivalent to `scandir(3)`, with a slightly different API. Returns a handle that 2570the user can pass to `uv.fs_scandir_next()`. 2571 2572**Note:** This function can be used synchronously or asynchronously. The request 2573userdata is always synchronously returned regardless of whether a callback is 2574provided and the same userdata is passed to the callback if it is provided. 2575 2576**Returns:** `uv_fs_t userdata` or `fail` 2577 2578### `uv.fs_scandir_next(fs)` 2579 2580**Parameters:** 2581- `fs`: `uv_fs_t userdata` 2582 2583Called on a `uv_fs_t` returned by `uv.fs_scandir()` to get the next directory 2584entry data as a `name, type` pair. When there are no more entries, `nil` is 2585returned. 2586 2587**Note:** This function only has a synchronous version. See `uv.fs_opendir` and 2588its related functions for an asynchronous version. 2589 2590**Returns:** `string, string` or `nil` or `fail` 2591 2592### `uv.fs_stat(path, [callback])` 2593 2594**Parameters:** 2595- `path`: `string` 2596- `callback`: `callable` (async version) or `nil` (sync version) 2597 - `err`: `nil` or `string` 2598 - `stat`: `table` or `nil` (see below) 2599 2600Equivalent to `stat(2)`. 2601 2602**Returns (sync version):** `table` or `fail` 2603- `dev` : `integer` 2604- `mode` : `integer` 2605- `nlink` : `integer` 2606- `uid` : `integer` 2607- `gid` : `integer` 2608- `rdev` : `integer` 2609- `ino` : `integer` 2610- `size` : `integer` 2611- `blksize` : `integer` 2612- `blocks` : `integer` 2613- `flags` : `integer` 2614- `gen` : `integer` 2615- `atime` : `table` 2616 - `sec` : `integer` 2617 - `nsec` : `integer` 2618- `mtime` : `table` 2619 - `sec` : `integer` 2620 - `nsec` : `integer` 2621- `ctime` : `table` 2622 - `sec` : `integer` 2623 - `nsec` : `integer` 2624- `birthtime` : `table` 2625 - `sec` : `integer` 2626 - `nsec` : `integer` 2627- `type` : `string` 2628 2629**Returns (async version):** `uv_fs_t userdata` 2630 2631### `uv.fs_fstat(fd, [callback])` 2632 2633**Parameters:** 2634- `fd`: `integer` 2635- `callback`: `callable` (async version) or `nil` (sync version) 2636 - `err`: `nil` or `string` 2637 - `stat`: `table` or `nil` (see `uv.fs_stat`) 2638 2639Equivalent to `fstat(2)`. 2640 2641**Returns (sync version):** `table` or `fail` (see `uv.fs_stat`) 2642 2643**Returns (async version):** `uv_fs_t userdata` 2644 2645### `uv.fs_lstat(path, [callback])` 2646 2647**Parameters:** 2648- `fd`: `integer` 2649- `callback`: `callable` (async version) or `nil` (sync version) 2650 - `err`: `nil` or `string` 2651 - `stat`: `table` or `nil` (see `uv.fs_stat`) 2652 2653Equivalent to `lstat(2)`. 2654 2655**Returns (sync version):** `table` or `fail` (see `uv.fs_stat`) 2656 2657**Returns (async version):** `uv_fs_t userdata` 2658 2659### `uv.fs_rename(path, new_path, [callback])` 2660 2661**Parameters:** 2662- `path`: `string` 2663- `new_path`: `string` 2664- `callback`: `callable` (async version) or `nil` (sync version) 2665 - `err`: `nil` or `string` 2666 - `success`: `boolean` or `nil` 2667 2668Equivalent to `rename(2)`. 2669 2670**Returns (sync version):** `boolean` or `fail` 2671 2672**Returns (async version):** `uv_fs_t userdata` 2673 2674### `uv.fs_fsync(fd, [callback])` 2675 2676**Parameters:** 2677- `fd`: `integer` 2678- `callback`: `callable` (async version) or `nil` (sync version) 2679 - `err`: `nil` or `string` 2680 - `success`: `boolean` or `nil` 2681 2682Equivalent to `fsync(2)`. 2683 2684**Returns (sync version):** `boolean` or `fail` 2685 2686**Returns (async version):** `uv_fs_t userdata` 2687 2688### `uv.fs_fdatasync(fd, [callback])` 2689 2690**Parameters:** 2691- `fd`: `integer` 2692- `callback`: `callable` (async version) or `nil` (sync version) 2693 - `err`: `nil` or `string` 2694 - `success`: `boolean` or `nil` 2695 2696Equivalent to `fdatasync(2)`. 2697 2698**Returns (sync version):** `boolean` or `fail` 2699 2700**Returns (async version):** `uv_fs_t userdata` 2701 2702### `uv.fs_ftruncate(fd, offset, [callback])` 2703 2704**Parameters:** 2705- `fd`: `integer` 2706- `offset`: `integer` 2707- `callback`: `callable` (async version) or `nil` (sync version) 2708 - `err`: `nil` or `string` 2709 - `success`: `boolean` or `nil` 2710 2711Equivalent to `ftruncate(2)`. 2712 2713**Returns (sync version):** `boolean` or `fail` 2714 2715**Returns (async version):** `uv_fs_t userdata` 2716 2717### `uv.fs_sendfile(out_fd, in_fd, in_offset, size, [callback])` 2718 2719**Parameters:** 2720- `out_fd`: `integer` 2721- `in_fd`: `integer` 2722- `in_offset`: `integer` 2723- `size`: `integer` 2724- `callback`: `callable` (async version) or `nil` (sync version) 2725 - `err`: `nil` or `string` 2726 - `bytes`: `integer` or `nil` 2727 2728Limited equivalent to `sendfile(2)`. Returns the number of bytes written. 2729 2730**Returns (sync version):** `integer` or `fail` 2731 2732**Returns (async version):** `uv_fs_t userdata` 2733 2734### `uv.fs_access(path, mode, [callback])` 2735 2736**Parameters:** 2737- `path`: `string` 2738- `mode`: `integer` 2739- `callback`: `callable` (async version) or `nil` (sync version) 2740 - `err`: `nil` or `string` 2741 - `permission`: `boolean` or `nil` 2742 2743Equivalent to `access(2)` on Unix. Windows uses `GetFileAttributesW()`. Access 2744`mode` can be an integer or a string containing `"R"` or `"W"` or `"X"`. 2745Returns `true` or `false` indicating access permission. 2746 2747**Returns (sync version):** `boolean` or `fail` 2748 2749**Returns (async version):** `uv_fs_t userdata` 2750 2751### `uv.fs_chmod(path, mode, [callback])` 2752 2753**Parameters:** 2754- `path`: `string` 2755- `mode`: `integer` 2756- `callback`: `callable` (async version) or `nil` (sync version) 2757 - `err`: `nil` or `string` 2758 - `success`: `boolean` or `nil` 2759 2760Equivalent to `chmod(2)`. 2761 2762**Returns (sync version):** `boolean` or `fail` 2763 2764**Returns (async version):** `uv_fs_t userdata` 2765 2766### `uv.fs_fchmod(fd, mode, [callback])` 2767 2768**Parameters:** 2769- `fd`: `integer` 2770- `mode`: `integer` 2771- `callback`: `callable` (async version) or `nil` (sync version) 2772 - `err`: `nil` or `string` 2773 - `success`: `boolean` or `nil` 2774 2775Equivalent to `fchmod(2)`. 2776 2777**Returns (sync version):** `boolean` or `fail` 2778 2779**Returns (async version):** `uv_fs_t userdata` 2780 2781### `uv.fs_utime(path, atime, mtime, [callback])` 2782 2783**Parameters:** 2784- `path`: `string` 2785- `atime`: `number` 2786- `mtime`: `number` 2787- `callback`: `callable` (async version) or `nil` (sync version) 2788 - `err`: `nil` or `string` 2789 - `success`: `boolean` or `nil` 2790 2791Equivalent to `utime(2)`. 2792 2793**Returns (sync version):** `boolean` or `fail` 2794 2795**Returns (async version):** `uv_fs_t userdata` 2796 2797### `uv.fs_futime(fd, atime, mtime, [callback])` 2798 2799**Parameters:** 2800- `fd`: `integer` 2801- `atime`: `number` 2802- `mtime`: `number` 2803- `callback`: `callable` (async version) or `nil` (sync version) 2804 - `err`: `nil` or `string` 2805 - `success`: `boolean` or `nil` 2806 2807Equivalent to `futime(2)`. 2808 2809**Returns (sync version):** `boolean` or `fail` 2810 2811**Returns (async version):** `uv_fs_t userdata` 2812 2813### `uv.fs_lutime(path, atime, mtime, [callback])` 2814 2815**Parameters:** 2816- `path`: `string` 2817- `atime`: `number` 2818- `mtime`: `number` 2819- `callback`: `callable` (async version) or `nil` (sync version) 2820 - `err`: `nil` or `string` 2821 - `success`: `boolean` or `nil` 2822 2823Equivalent to `lutime(2)`. 2824 2825**Returns (sync version):** `boolean` or `fail` 2826 2827**Returns (async version):** `uv_fs_t userdata` 2828 2829### `uv.fs_link(path, new_path, [callback])` 2830 2831**Parameters:** 2832- `path`: `string` 2833- `new_path`: `string` 2834- `callback`: `callable` (async version) or `nil` (sync version) 2835 - `err`: `nil` or `string` 2836 - `success`: `boolean` or `nil` 2837 2838Equivalent to `link(2)`. 2839 2840**Returns (sync version):** `boolean` or `fail` 2841 2842**Returns (async version):** `uv_fs_t userdata` 2843 2844### `uv.fs_symlink(path, new_path, [flags], [callback])` 2845 2846**Parameters:** 2847- `path`: `string` 2848- `new_path`: `string` 2849- `flags`: `table`, `integer`, or `nil` 2850 - `dir`: `boolean` 2851 - `junction`: `boolean` 2852- `callback`: `callable` (async version) or `nil` (sync version) 2853 - `err`: `nil` or `string` 2854 - `success`: `boolean` or `nil` 2855 2856Equivalent to `symlink(2)`. If the `flags` parameter is omitted, then the 3rd parameter will be treated as the `callback`. 2857 2858**Returns (sync version):** `boolean` or `fail` 2859 2860**Returns (async version):** `uv_fs_t userdata` 2861 2862### `uv.fs_readlink(path, [callback])` 2863 2864**Parameters:** 2865- `path`: `string` 2866- `callback`: `callable` (async version) or `nil` (sync version) 2867 - `err`: `nil` or `string` 2868 - `path`: `string` or `nil` 2869 2870Equivalent to `readlink(2)`. 2871 2872**Returns (sync version):** `string` or `fail` 2873 2874**Returns (async version):** `uv_fs_t userdata` 2875 2876### `uv.fs_realpath(path, [callback])` 2877 2878**Parameters:** 2879- `path`: `string` 2880- `callback`: `callable` (async version) or `nil` (sync version) 2881 - `err`: `nil` or `string` 2882 - `path`: `string` or `nil` 2883 2884Equivalent to `realpath(3)`. 2885 2886**Returns (sync version):** `string` or `fail` 2887 2888**Returns (async version):** `uv_fs_t userdata` 2889 2890### `uv.fs_chown(path, uid, gid, [callback])` 2891 2892**Parameters:** 2893- `path`: `string` 2894- `uid`: `integer` 2895- `gid`: `integer` 2896- `callback`: `callable` (async version) or `nil` (sync version) 2897 - `err`: `nil` or `string` 2898 - `success`: `boolean` or `nil` 2899 2900Equivalent to `chown(2)`. 2901 2902**Returns (sync version):** `boolean` or `fail` 2903 2904**Returns (async version):** `uv_fs_t userdata` 2905 2906### `uv.fs_fchown(fd, uid, gid, [callback])` 2907 2908**Parameters:** 2909- `fd`: `integer` 2910- `uid`: `integer` 2911- `gid`: `integer` 2912- `callback`: `callable` (async version) or `nil` (sync version) 2913 - `err`: `nil` or `string` 2914 - `success`: `boolean` or `nil` 2915 2916Equivalent to `fchown(2)`. 2917 2918**Returns (sync version):** `boolean` or `fail` 2919 2920**Returns (async version):** `uv_fs_t userdata` 2921 2922### `uv.fs_lchown(fd, uid, gid, [callback])` 2923 2924**Parameters:** 2925- `fd`: `integer` 2926- `uid`: `integer` 2927- `gid`: `integer` 2928- `callback`: `callable` (async version) or `nil` (sync version) 2929 - `err`: `nil` or `string` 2930 - `success`: `boolean` or `nil` 2931 2932Equivalent to `lchown(2)`. 2933 2934**Returns (sync version):** `boolean` or `fail` 2935 2936**Returns (async version):** `uv_fs_t userdata` 2937 2938### `uv.fs_copyfile(path, new_path, [flags], [callback])` 2939 2940**Parameters:** 2941- `path`: `string` 2942- `new_path`: `string` 2943- `flags`: `table`, `integer`, or `nil` 2944 - `excl`: `boolean` 2945 - `ficlone`: `boolean` 2946 - `ficlone_force`: `boolean` 2947- `callback`: `callable` (async version) or `nil` (sync version) 2948 - `err`: `nil` or `string` 2949 - `success`: `boolean` or `nil` 2950 2951Copies a file from path to new_path. If the `flags` parameter is omitted, then the 3rd parameter will be treated as the `callback`. 2952 2953**Returns (sync version):** `boolean` or `fail` 2954 2955**Returns (async version):** `uv_fs_t userdata` 2956 2957### `uv.fs_opendir(path, [callback, [entries]])` 2958 2959**Parameters:** 2960- `path`: `string` 2961- `callback`: `callable` (async version) or `nil` (sync version) 2962 - `err`: `nil` or `string` 2963 - `dir`: `uv_dir_t userdata` or `nil` 2964- `entries`: `integer` or `nil` 2965 2966Opens path as a directory stream. Returns a handle that the user can pass to 2967`uv.fs_readdir()`. The `entries` parameter defines the maximum number of entries 2968that should be returned by each call to `uv.fs_readdir()`. 2969 2970**Returns (sync version):** `uv_dir_t userdata` or `fail` 2971 2972**Returns (async version):** `uv_fs_t userdata` 2973 2974### `uv.fs_readdir(dir, [callback])` 2975 2976**Parameters:** 2977- `dir`: `uv_dir_t userdata` 2978- `callback`: `callable` (async version) or `nil` (sync version) 2979 - `err`: `nil` or `string` 2980 - `entries`: `table` or `nil` (see below) 2981 2982Iterates over the directory stream `uv_dir_t` returned by a successful 2983`uv.fs_opendir()` call. A table of data tables is returned where the number 2984of entries `n` is equal to or less than the `entries` parameter used in 2985the associated `uv.fs_opendir()` call. 2986 2987**Returns (sync version):** `table` or `fail` 2988- `[1, 2, 3, ..., n]` : `table` 2989 - `name` : `string` 2990 - `type` : `string` 2991 2992**Returns (async version):** `uv_fs_t userdata` 2993 2994### `uv.fs_closedir(dir, [callback])` 2995 2996**Parameters:** 2997- `dir`: `uv_dir_t userdata` 2998- `callback`: `callable` (async version) or `nil` (sync version) 2999 - `err`: `nil` or `string` 3000 - `success`: `boolean` or `nil` 3001 3002Closes a directory stream returned by a successful `uv.fs_opendir()` call. 3003 3004**Returns (sync version):** `boolean` or `fail` 3005 3006**Returns (async version):** `uv_fs_t userdata` 3007 3008### `uv.fs_statfs(path, [callback])` 3009 3010**Parameters:** 3011- `path`: `string` 3012- `callback`: `callable` (async version) or `nil` (sync version) 3013 - `err`: `nil` or `string` 3014 - `table` or `nil` (see below) 3015 3016Equivalent to `statfs(2)`. 3017 3018**Returns** `table` or `nil` 3019- `type` : `integer` 3020- `bsize` : `integer` 3021- `blocks` : `integer` 3022- `bfree` : `integer` 3023- `bavail` : `integer` 3024- `files` : `integer` 3025- `ffree` : `integer` 3026 3027## Thread pool work scheduling 3028 3029[Thread pool work scheduling]: #thread-pool-work-scheduling 3030 3031Libuv provides a threadpool which can be used to run user code and get notified 3032in the loop thread. This threadpool is internally used to run all file system 3033operations, as well as `getaddrinfo` and `getnameinfo` requests. 3034 3035```lua 3036local function work_callback(a, b) 3037 return a + b 3038end 3039 3040local function after_work_callback(c) 3041 print("The result is: " .. c) 3042end 3043 3044local work = uv.new_work(work_callback, after_work_callback) 3045 3046work:queue(1, 2) 3047 3048-- output: "The result is: 3" 3049``` 3050 3051### `uv.new_work(work_callback, after_work_callback)` 3052 3053**Parameters:** 3054- `work_callback`: `function` 3055 - `...`: `threadargs` passed to/from `uv.queue_work(work_ctx, ...)` 3056- `after_work_callback`: `function` 3057 - `...`: `threadargs` returned from `work_callback` 3058 3059Creates and initializes a new `luv_work_ctx_t` (not `uv_work_t`). Returns the 3060Lua userdata wrapping it. 3061 3062**Returns:** `luv_work_ctx_t userdata` 3063 3064### `uv.queue_work(work_ctx, ...)` 3065 3066> method form `work_ctx:queue(...)` 3067 3068**Parameters:** 3069- `work_ctx`: `luv_work_ctx_t userdata` 3070- `...`: `threadargs` 3071 3072Queues a work request which will run `work_callback` in a new Lua state in a 3073thread from the threadpool with any additional arguments from `...`. Values 3074returned from `work_callback` are passed to `after_work_callback`, which is 3075called in the main loop thread. 3076 3077**Returns:** `boolean` or `fail` 3078 3079## DNS utility functions 3080 3081[DNS utility functions]: #dns-utility-functions 3082 3083### `uv.getaddrinfo(host, service, [hints, [callback]])` 3084 3085**Parameters:** 3086- `host`: `string` or `nil` 3087- `service`: `string` or `nil` 3088- `hints`: `table` or `nil` 3089 - `family`: `integer` or `string` or `nil` 3090 - `socktype`: `integer` or `string` or `nil` 3091 - `protocol`: `integer` or `string` or `nil` 3092 - `addrconfig`: `boolean` or `nil` 3093 - `v4mapped`: `boolean` or `nil` 3094 - `all`: `boolean` or `nil` 3095 - `numerichost`: `boolean` or `nil` 3096 - `passive`: `boolean` or `nil` 3097 - `numericserv`: `boolean` or `nil` 3098 - `canonname`: `boolean` or `nil` 3099- `callback`: `callable` (async version) or `nil` (sync version) 3100 - `err`: `nil` or `string` 3101 - `addresses`: `table` or `nil` (see below) 3102 3103Equivalent to `getaddrinfo(3)`. Either `node` or `service` may be `nil` but not 3104both. 3105 3106**Returns (sync version):** `table` or `fail` 3107- `[1, 2, 3, ..., n]` : `table` 3108 - `addr` : `string` 3109 - `family` : `string` 3110 - `port` : `integer` or `nil` 3111 - `socktype` : `string` 3112 - `protocol` : `string` 3113 - `canonname` : `string` or `nil` 3114 3115**Returns (async version):** `uv_getaddrinfo_t userdata` or `fail` 3116 3117### `uv.getnameinfo(address, [callback])` 3118 3119**Parameters:** 3120- `address`: `table` 3121 - `ip`: `string` or `nil` 3122 - `port`: `integer` or `nil` 3123 - `family`: `string` or `integer` or `nil` 3124- `callback`: `callable` (async version) or `nil` (sync version) 3125 - `err`: `nil` or `sring` 3126 - `host`: `string` or `nil` 3127 - `service`: `string` or `nil` 3128 3129Equivalent to `getnameinfo(3)`. 3130 3131**Returns (sync version):** `string, string` or `fail` 3132 3133**Returns (async version):** `uv_getnameinfo_t userdata` or `fail` 3134 3135## Threading and synchronization utilities 3136 3137[Threading and synchronization utilities]: #threading-and-synchronization-utilities 3138 3139Libuv provides cross-platform implementations for multiple threading an 3140 synchronization primitives. The API largely follows the pthreads API. 3141 3142### `uv.new_thread([options], entry, ...)` 3143 3144**Parameters:** 3145- `options`: `table` or `nil` 3146 - `stack_size`: `integer` or `nil` 3147- `entry`: `function` 3148- `...`: `threadargs` passed to `entry` 3149 3150Creates and initializes a `luv_thread_t` (not `uv_thread_t`). Returns the Lua 3151userdata wrapping it and asynchronously executes `entry`, which can be either 3152a Lua function or a Lua function dumped to a string. Additional arguments `...` 3153are passed to the `entry` function and an optional `options` table may be 3154provided. Currently accepted `option` fields are `stack_size`. 3155 3156**Returns:** `luv_thread_t userdata` or `fail` 3157 3158### `uv.thread_equal(thread, other_thread)` 3159 3160> method form `thread:equal(other_thread)` 3161 3162**Parameters:** 3163- `thread`: `luv_thread_t userdata` 3164- `other_thread`: `luv_thread_t userdata` 3165 3166Returns a boolean indicating whether two threads are the same. This function is 3167equivalent to the `__eq` metamethod. 3168 3169**Returns:** `boolean` 3170 3171### `uv.thread_self()` 3172 3173Returns the handle for the thread in which this is called. 3174 3175**Returns:** `luv_thread_t` 3176 3177### `uv.thread_join(thread)` 3178 3179> method form `thread:join()` 3180 3181**Parameters:** 3182- `thread`: `luv_thread_t userdata` 3183 3184Waits for the `thread` to finish executing its entry function. 3185 3186**Returns:** `boolean` or `fail` 3187 3188### `uv.sleep(msec)` 3189 3190**Parameters:** 3191- `msec`: `integer` 3192 3193Pauses the thread in which this is called for a number of milliseconds. 3194 3195**Returns:** Nothing. 3196 3197## Miscellaneous utilities 3198 3199[Miscellaneous utilities]: #miscellaneous-utilities 3200 3201### `uv.exepath()` 3202 3203Returns the executable path. 3204 3205**Returns:** `string` or `fail` 3206 3207### `uv.cwd()` 3208 3209Returns the current working directory. 3210 3211**Returns:** `string` or `fail` 3212 3213### `uv.chdir(cwd)` 3214 3215**Parameters:** 3216- `cwd`: `string` 3217 3218Sets the current working directory with the string `cwd`. 3219 3220**Returns:** `0` or `fail` 3221 3222### `uv.get_process_title()` 3223 3224Returns the title of the current process. 3225 3226**Returns:** `string` or `fail` 3227 3228### `uv.set_process_title(title)` 3229 3230**Parameters:** 3231- `title`: `string` 3232 3233Sets the title of the current process with the string `title`. 3234 3235**Returns:** `0` or `fail` 3236 3237### `uv.get_total_memory()` 3238 3239Returns the current total system memory in bytes. 3240 3241**Returns:** `number` 3242 3243### `uv.get_free_memory()` 3244 3245Returns the current free system memory in bytes. 3246 3247**Returns:** `number` 3248 3249### `uv.get_constrained_memory()` 3250 3251Gets the amount of memory available to the process in bytes based on limits 3252imposed by the OS. If there is no such constraint, or the constraint is unknown, 32530 is returned. Note that it is not unusual for this value to be less than or 3254greater than the total system memory. 3255 3256**Returns:** `number` 3257 3258### `uv.resident_set_memory()` 3259 3260Returns the resident set size (RSS) for the current process. 3261 3262**Returns:** `integer` or `fail` 3263 3264### `uv.getrusage()` 3265 3266Returns the resource usage. 3267 3268**Returns:** `table` or `fail` 3269- `utime` : `table` (user CPU time used) 3270 - `sec` : `integer` 3271 - `usec` : `integer` 3272- `stime` : `table` (system CPU time used) 3273 - `sec` : `integer` 3274 - `usec` : `integer` 3275- `maxrss` : `integer` (maximum resident set size) 3276- `ixrss` : `integer` (integral shared memory size) 3277- `idrss` : `integer` (integral unshared data size) 3278- `isrss` : `integer` (integral unshared stack size) 3279- `minflt` : `integer` (page reclaims (soft page faults)) 3280- `majflt` : `integer` (page faults (hard page faults)) 3281- `nswap` : `integer` (swaps) 3282- `inblock` : `integer` (block input operations) 3283- `oublock` : `integer` (block output operations) 3284- `msgsnd` : `integer` (IPC messages sent) 3285- `msgrcv` : `integer` (IPC messages received) 3286- `nsignals` : `integer` (signals received) 3287- `nvcsw` : `integer` (voluntary context switches) 3288- `nivcsw` : `integer` (involuntary context switches) 3289 3290### `uv.cpu_info()` 3291 3292Returns information about the CPU(s) on the system as a table of tables for each 3293CPU found. 3294 3295**Returns:** `table` or `fail` 3296- `[1, 2, 3, ..., n]` : `table` 3297 - `model` : `string` 3298 - `speed` : `number` 3299 - `times` : `table` 3300 - `user` : `number` 3301 - `nice` : `number` 3302 - `sys` : `number` 3303 - `idle` : `number` 3304 - `irq` : `number` 3305 3306### `uv.getpid()` 3307 3308**Deprecated:** Please use `uv.os_getpid()` instead. 3309 3310### `uv.getuid()` 3311 3312Returns the user ID of the process. 3313 3314**Returns:** `integer` 3315 3316**Note:** This is not a libuv function and is not supported on Windows. 3317 3318### `uv.getgid()` 3319 3320Returns the group ID of the process. 3321 3322**Returns:** `integer` 3323 3324**Note:** This is not a libuv function and is not supported on Windows. 3325 3326### `uv.setuid(id)` 3327 3328**Parameters:** 3329- `id`: `integer` 3330 3331Sets the user ID of the process with the integer `id`. 3332 3333**Returns:** Nothing. 3334 3335**Note:** This is not a libuv function and is not supported on Windows. 3336 3337### `uv.setgid(id)` 3338 3339**Parameters:** 3340- `id`: `integer` 3341 3342Sets the group ID of the process with the integer `id`. 3343 3344**Returns:** Nothing. 3345 3346**Note:** This is not a libuv function and is not supported on Windows. 3347 3348### `uv.hrtime()` 3349 3350Returns a current high-resolution time in nanoseconds as a number. This is 3351relative to an arbitrary time in the past. It is not related to the time of day 3352and therefore not subject to clock drift. The primary use is for measuring 3353time between intervals. 3354 3355**Returns:** `number` 3356 3357### `uv.uptime()` 3358 3359Returns the current system uptime in seconds. 3360 3361**Returns:** `number` or `fail` 3362 3363### `uv.print_all_handles()` 3364 3365Prints all handles associated with the main loop to stderr. The format is 3366`[flags] handle-type handle-address`. Flags are `R` for referenced, `A` for 3367active and `I` for internal. 3368 3369**Returns:** Nothing. 3370 3371**Note:** This is not available on Windows. 3372 3373**Warning:** This function is meant for ad hoc debugging, there are no API/ABI 3374stability guarantees. 3375 3376### `uv.print_active_handles()` 3377 3378The same as `uv.print_all_handles()` except only active handles are printed. 3379 3380**Returns:** Nothing. 3381 3382**Note:** This is not available on Windows. 3383 3384**Warning:** This function is meant for ad hoc debugging, there are no API/ABI 3385stability guarantees. 3386 3387### `uv.guess_handle(fd)` 3388 3389**Parameters:** 3390- `fd`: `integer` 3391 3392Used to detect what type of stream should be used with a given file 3393descriptor `fd`. Usually this will be used during initialization to guess the 3394type of the stdio streams. 3395 3396**Returns:** `string` 3397 3398### `uv.gettimeofday()` 3399 3400Cross-platform implementation of `gettimeofday(2)`. Returns the seconds and 3401microseconds of a unix time as a pair. 3402 3403**Returns:** `integer, integer` or `fail` 3404 3405### `uv.interface_addresses()` 3406 3407Returns address information about the network interfaces on the system in a 3408table. Each table key is the name of the interface while each associated value 3409is an array of address information where fields are `ip`, `family`, `netmask`, 3410`internal`, and `mac`. 3411 3412**Returns:** `table` 3413- `[name(s)]` : `table` 3414 - `ip` : `string` 3415 - `family` : `string` 3416 - `netmask` : `string` 3417 - `internal` : `boolean` 3418 - `mac` : `string` 3419 3420### `uv.if_indextoname(ifindex)` 3421 3422**Parameters:** 3423- `ifindex`: `integer` 3424 3425IPv6-capable implementation of `if_indextoname(3)`. 3426 3427**Returns:** `string` or `fail` 3428 3429### `uv.if_indextoiid(ifindex)` 3430 3431**Parameters:** 3432- `ifindex`: `integer` 3433 3434Retrieves a network interface identifier suitable for use in an IPv6 scoped 3435address. On Windows, returns the numeric `ifindex` as a string. On all other 3436platforms, `uv.if_indextoname()` is used. 3437 3438**Returns:** `string` or `fail` 3439 3440### `uv.loadavg()` 3441 3442Returns the load average as a triad. Not supported on Windows. 3443 3444**Returns:** `number, number, number` 3445 3446### `uv.os_uname()` 3447 3448Returns system information. 3449 3450**Returns:** `table` 3451- `sysname` : `string` 3452- `release` : `string` 3453- `version` : `string` 3454- `machine` : `string` 3455 3456### `uv.os_gethostname()` 3457 3458Returns the hostname. 3459 3460**Returns:** `string` 3461 3462### `uv.os_getenv(name, [size])` 3463 3464**Parameters:** 3465- `name`: `string` 3466- `size`: `integer` (default = `LUAL_BUFFERSIZE`) 3467 3468Returns the environment variable specified by `name` as string. The internal 3469buffer size can be set by defining `size`. If omitted, `LUAL_BUFFERSIZE` is 3470used. If the environment variable exceeds the storage available in the internal 3471buffer, `ENOBUFS` is returned. If no matching environment variable exists, 3472`ENOENT` is returned. 3473 3474**Returns:** `string` or `fail` 3475 3476**Warning:** This function is not thread safe. 3477 3478### `uv.os_setenv(name, value)` 3479 3480**Parameters:** 3481- `name`: `string` 3482- `value`: `string` 3483 3484Sets the environmental variable specified by `name` with the string `value`. 3485 3486**Returns:** `boolean` or `fail` 3487 3488**Warning:** This function is not thread safe. 3489 3490### `uv.os_unsetenv()` 3491 3492**Returns:** `boolean` or `fail` 3493 3494**Warning:** This function is not thread safe. 3495 3496### `uv.os_environ()` 3497 3498Returns all environmental variables as a dynamic table of names associated with 3499their corresponding values. 3500 3501**Returns:** `table` 3502 3503**Warning:** This function is not thread safe. 3504 3505### `uv.os_homedir()` 3506 3507**Returns:** `string` or `fail` 3508 3509**Warning:** This function is not thread safe. 3510 3511### `uv.os_tmpdir()` 3512 3513**Returns:** `string` or `fail` 3514 3515**Warning:** This function is not thread safe. 3516 3517### `uv.os_get_passwd()` 3518 3519Returns password file information. 3520 3521**Returns:** `table` 3522- `username` : `string` 3523- `uid` : `integer` 3524- `gid` : `integer` 3525- `shell` : `string` 3526- `homedir` : `string` 3527 3528### `uv.os_getpid()` 3529 3530Returns the current process ID. 3531 3532**Returns:** `number` 3533 3534### `uv.os_getppid()` 3535 3536Returns the parent process ID. 3537 3538**Returns:** `number` 3539 3540### `uv.os_getpriority(pid)` 3541 3542**Parameters:** 3543- `pid`: `integer` 3544 3545Returns the scheduling priority of the process specified by `pid`. 3546 3547**Returns:** `number` or `fail` 3548 3549### `uv.os_setpriority(pid, priority)` 3550 3551**Parameters:** 3552- `pid`: `integer` 3553- `priority`: `integer` 3554 3555Sets the scheduling priority of the process specified by `pid`. The `priority` 3556range is between -20 (high priority) and 19 (low priority). 3557 3558**Returns:** `boolean` or `fail` 3559 3560### `uv.random(len, flags, [callback])` 3561 3562**Parameters:** 3563- `len`: `integer` 3564- `flags`: `nil` (see below) 3565- `callback`: `callable` (async version) or `nil` (sync version) 3566 - `err`: `nil` or `string` 3567 - `bytes`: `string` or `nil` 3568 3569Fills a string of length `len` with cryptographically strong random bytes 3570acquired from the system CSPRNG. `flags` is reserved for future extension 3571and must currently be `nil` or `0` or `{}`. 3572 3573Short reads are not possible. When less than `len` random bytes are available, 3574a non-zero error value is returned or passed to the callback. If the callback 3575is omitted, this function is completed synchronously. 3576 3577The synchronous version may block indefinitely when not enough entropy is 3578available. The asynchronous version may not ever finish when the system is 3579low on entropy. 3580 3581**Returns (sync version):** `string` or `fail` 3582 3583**Returns (async version):** `0` or `fail` 3584 3585## Metrics operations 3586 3587[Metrics operations]: #metrics-operations 3588 3589### `uv.metrics_idle_time()` 3590 3591Retrieve the amount of time the event loop has been idle in the kernel’s event 3592provider (e.g. `epoll_wait`). The call is thread safe. 3593 3594The return value is the accumulated time spent idle in the kernel’s event 3595provider starting from when the [`uv_loop_t`][] was configured to collect the idle time. 3596 3597**Note:** The event loop will not begin accumulating the event provider’s idle 3598time until calling `loop_configure` with `"metrics_idle_time"`. 3599 3600**Returns:** `number` 3601 3602--- 3603 3604[luv]: https://github.com/luvit/luv 3605[luvit]: https://github.com/luvit/luvit 3606[libuv]: https://github.com/libuv/libuv 3607[libuv documentation page]: http://docs.libuv.org/ 3608[libuv API documentation]: http://docs.libuv.org/en/v1.x/api.html 3609