Giter Club home page Giter Club logo

core_modules's Introduction

Node FS

Callback, Promise, or Synchronus
Only Promise and examples for only what works on all platforms
All depreciated content as of 4/23 is left out.

fsPExamples.js

fsPromises Examples

fsPromises.access(path[, mode]) Examples: 4
Tests a user's permissions for the file or directory specified by path. The mode argument is an optional integer that specifies the accessibility checks to be performed. mode should be either the value fs.constants.F_OK or a mask consisting of the bitwise OR of any of fs.constants.R_OK, fs.constants.W_OK, and fs.constants.X_OK
File access constants The following constants are meant for use as the mode parameter passed to fsPromises.access(), fs.access(), and fs.accessSync().

Constant Description F_OK Flag indicating that the file is visible to the calling process. This is useful for determining if a file exists, but says nothing about rwx permissions. Default if no mode is specified. R_OK Flag indicating that the file can be read by the calling process. W_OK Flag indicating that the file can be written by the calling process. X_OK Flag indicating that the file can be executed by the calling process. This has no effect on Windows (will behave like fs.constants.F_OK).

fsPromises.appendFile(path, data[, options])
fsPromises.chmod(path, mode)
fsPromises.chown(path, uid, gid)
fsPromises.copyFile(src, dest[, mode])
fsPromises.cp(src, dest[, options])(experimental 4/23)
fsPromises.lchmod(path, mode)
fsPromises.lchown(path, uid, gid)
fsPromises.lutimes(path, atime, mtime)
fsPromises.link(existingPath, newPath)
fsPromises.lstat(path[, options])
fsPromises.mkdir(path[, options])
fsPromises.mkdtemp(prefix[, options])
fsPromises.open(path, flags[, mode])
fsPromises.opendir(path[, options])
fsPromises.readdir(path[, options])
fsPromises.readFile(path[, options])
fsPromises.readlink(path[, options])
fsPromises.realpath(path[, options])
fsPromises.rename(oldPath, newPath)
fsPromises.rmdir(path[, options])
fsPromises.rm(path[, options])
fsPromises.stat(path[, options])
fsPromises.statfs(path[, options])
fsPromises.symlink(target, path[, type])
fsPromises.truncate(path[, len])
fsPromises.unlink(path)
fsPromises.utimes(path, atime, mtime)
fsPromises.watch(filename[, options])
fsPromises.writeFile(file, data[, options])
fsPromises.constants

fileHandles

A FileHandle object is an object wrapper for a numeric file descriptor.

Instances of the FileHandle object are created by the fsPromises.open() method.

All FileHandle objects are EventEmitters.

EVENTS:

The 'close' event is emitted when the has been closed and can no longer be used.

METHODS

fsPromises.open(path, flags[, mode]) Examples: 1,2

path string | Buffer | URL flags string | number See support of file system flags. Default: 'r'. mode string | integer Sets the file mode (permission and sticky bits) if the file is created. Default: 0o666 (readable and writable) Returns: Promise Fulfills with a FileHandle object. Opens a FileHandle.

Refer to the POSIX open(2) documentation for more detail.

Some characters (< > : " / \ | ? *) are reserved under Windows as documented by Naming Files, Paths, and Namespaces. Under NTFS, if the filename contains a colon, Node.js will open a file system stream, as described by this MSDN page.

File system flags# The following flags are available wherever the flag option takes a string.

'a': Open file for appending. The file is created if it does not exist.

'ax': Like 'a' but fails if the path exists.

'a+': Open file for reading and appending. The file is created if it does not exist.

'ax+': Like 'a+' but fails if the path exists.

'as': Open file for appending in synchronous mode. The file is created if it does not exist.

'as+': Open file for reading and appending in synchronous mode. The file is created if it does not exist.

'r': Open file for reading. An exception occurs if the file does not exist.

'r+': Open file for reading and writing. An exception occurs if the file does not exist.

'rs+': Open file for reading and writing in synchronous mode. Instructs the operating system to bypass the local file system cache.

This is primarily useful for opening files on NFS mounts as it allows skipping the potentially stale local cache. It has a very real impact on I/O performance so using this flag is not recommended unless it is needed.

This doesn't turn fs.open() or fsPromises.open() into a synchronous blocking call. If synchronous operation is desired, something like fs.openSync() should be used.

'w': Open file for writing. The file is created (if it does not exist) or truncated (if it exists).

'wx': Like 'w' but fails if the path exists.

'w+': Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).

'wx+': Like 'w+' but fails if the path exists.

flag can also be a number as documented by open(2); commonly used constants are available from fs.constants. On Windows, flags are translated to their equivalent ones where applicable, e.g. O_WRONLY to FILE_GENERIC_WRITE, or O_EXCL|O_CREAT to CREATE_NEW, as accepted by CreateFileW.

The exclusive flag 'x' (O_EXCL flag in open(2)) causes the operation to return an error if the path already exists. On POSIX, if the path is a symbolic link, using O_EXCL returns an error even if the link is to a path that does not exist. The exclusive flag might not work with network file systems.

On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.

Modifying a file rather than replacing it may require the flag option to be set to 'r+' rather than the default 'w'.

The behavior of some flags are platform-specific. As such, opening a directory on macOS and Linux with the 'a+' flag, as in the example below, will return an error. In contrast, on Windows and FreeBSD, a file descriptor or a FileHandle will be returned.

// macOS and Linux fs.open('', 'a+', (err, fd) => { // => [Error: EISDIR: illegal operation on a directory, open ] });

// Windows and FreeBSD fs.open('', 'a+', (err, fd) => { // => null, }); On Windows, opening an existing hidden file using the 'w' flag (either through fs.open(), fs.writeFile(), or fsPromises.open()) will fail with EPERM. Existing hidden files can be opened for writing with the 'r+' flag.

A call to fs.ftruncate() or filehandle.truncate() can be used to reset the file contents.

close

filehandle.appendFile(data[, options]) Examples: 1, 2
data string | Buffer | TypedArray | DataView | AsyncIterable | Iterable | Stream options Object | string encoding string | null Default: 'utf8' Returns: Promise Fulfills with undefined upon success. Alias of filehandle.writeFile().

When operating on file handles, the mode cannot be changed from what it was set to with fsPromises.open(). Therefore, this is equivalent to filehandle.writeFile().

filehandle.chmod(mode) Examples: 4
Note: The Windows platform only supports the changing of the write permission. It also does not support the distinction between the permissions of user, group, or others. filehandle.chown(uid, gid)
filehandle.close() Examples: 1, 2
Closes the file handle after waiting for any pending operation on the handle to complete.
filehandle.createReadStream([options]) Example: 1
filehandle.createWriteStream([options])
filehandle.datasync()
Forces all currently queued I/O operations associated with the file to the operating system's synchronized I/O completion state. Refer to the POSIX fdatasync(2) documentation for details.
Unlike filehandle.sync this method does not flush modified metadata.
filehandle.fd
The numeric file descriptor managed by the FileHandle object.
filehandle.read(buffer, offset, length, position) Example 1
filehandle.readableWebStream() (experimental 4/23)
filehandle.readFile(options) Examples: 1
filehandle.readLines([options]) Examples: 2
filehandle.readv(buffers[, position])
filehandle.stat([options]) Examples: 2
filehandle.sync() Examples: 2
Request that all data for the open file descriptor is flushed to the storage device. The specific implementation is operating system and device specific. Refer to the POSIX fsync(2) documentation for more detail.
filehandle.truncate(len) Examples: 2
**filehandle.utimes(atime, mtime)**Examples: 3
Change the file system timestamps of the object referenced by the FileHandle then resolves the promise with no arguments upon success.
filehandle.write(buffer, offset[, length[, position]])
filehandle.write(buffer[, options])
filehandle.write(string[, position[, encoding]])
It is unsafe to use filehandle.write() multiple times on the same file without waiting for the promise to be resolved (or rejected). For this scenario, use filehandle.createWriteStream().
On Linux, positional writes do not work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.
filehandle.writeFile(data, options) Examples: 3
filehandle.writev(buffers[, position])


fsPromises.access(path[, mode])

Examples:

  1. Open File, appendFile(string), Close File, Emmit File closed message, Open File again, Create a readStream, Use Stream Commands to stream(close, push, read), Read file into buffer, Close File, Open file again and use readFile to read the file, Close File

  2. Open File, append some lines, close file, open file, read a line at a time, close file, Open file, truncate file, Read file into buffer, close file

  3. open file, change meta dates, replace file text, close file

  4. Check file visibility and read, write, execute permissions.

Net

The node:net module provides an asynchronous network API for creating stream-based TCP or IPC(Inter-Proccess-Communications) servers (net.createServer()) and clients (net.createConnection()).

Class: net.BlockList

The BlockList object can be used with some network APIs to specify rules for disabling inbound or outbound access to specific IP addresses, IP ranges, or IP subnets.

blockList.addAddress(address[, type])
blockList.addRange(start, end[, type])
blockList.addSubnet(net, prefix[, type])
blockList.rules

Class: net.SocketAddress

new net.SocketAddress([options])
socketaddress.address
socketaddress.family
socketaddress.flowlabel
socketaddress.port

Class: net.Server

Extends: EventEmitter
This class is used to create a TCP or IPC server.

new net.Server([options][, connectionListener])
net.Server is an EventEmitter with the following events:
Event: 'close'
Event: 'connection'
Event: 'error'
Event: 'listening'
Event: 'drop'
When the number of connections reaches the threshold of server.maxConnections, the server will drop new connections and emit 'drop' event instead.
server.address()
server.close([callback])
server.getConnections(callback)
server.listen()
server.listen(handle[, backlog][, callback])
server.listen(options[, callback])
server.listen(path[, backlog][, callback])
server.listen([port[, host[, backlog]]][, callback]
server.listening
server.maxConnections
server.ref()
server.unref()

Class: net.Socket

Extends: stream.Duplex
This class is an abstraction of a TCP socket or a streaming IPC endpoint (uses named pipes on Windows, and Unix domain sockets otherwise). It is also an EventEmitter.
A net.Socket can be created by the user and used directly to interact with a server. For example, it is returned by net.createConnection(), so the user can use it to talk to the server.

It can also be created by Node.js and passed to the user when a connection is received. For example, it is passed to the listeners of a 'connection' event emitted on a net.Server, so the user can use it to interact with the client.

new net.Socket([options])
The newly created socket can be either a TCP socket or a streaming IPC endpoint, depending on what it connect() to.

Event: 'close'
Event: 'connect'
Event: 'data'
Event: 'drain'
Event: 'end'
Event: 'error'
Event: 'lookup'
Event: 'ready'
Event: 'timeout'
socket.address()
socket.bytesRead
socket.bytesWritten
socket.connect()
This function is asynchronous. When the connection is established, the 'connect' event will be emitted. If there is a problem connecting, instead of a 'connect' event, an 'error' event will be emitted with the error passed to the 'error' listener. The last parameter connectListener, if supplied, will be added as a listener for the 'connect' event once.
socket.connect(path[, connectListener])
socket.connect(port[, host][, connectListener])
socket.connecting
socket.destroy([error])
socket.destroyed
socket.destroySoon()
socket.end([data[, encoding]][, callback])
socket.localAddress
socket.localPort
socket.localFamily
socket.pause()
socket.pending
socket.ref()
socket.remoteAddress
socket.remoteFamily
socket.remotePort
socket.resetAndDestroy()
socket.resume()
socket.setEncoding([encoding])
socket.setKeepAlive([enable][, initialDelay])
socket.setNoDelay([noDelay])
socket.setTimeout(timeout[, callback])
socket.timeout
socket.unref()
socket.write(data[, encoding][, callback])
net.connect()
net.connect(options[, connectListener])
net.connect(path[, connectListener])
net.connect(port[, host][, connectListener])
net.createConnection()
net.createConnection(path[, connectListener])
net.createConnection(port[, host][, connectListener])
net.createServer([options][, connectionListener])
net.isIP(input)
net.isIPv4(input)
net.isIPv6(input)

HTTP

The HTTP interfaces in Node.js are designed to support many features of the protocol which have been traditionally difficult to use. In particular, large, possibly chunk-encoded, messages. The interface is careful to never buffer entire requests or responses, so the user is able to stream data.

In order to support the full spectrum of possible HTTP applications, the Node.js HTTP API is very low-level. It deals with stream handling and message parsing only. It parses a message into headers and body but it does not parse the actual headers or the body.

http.METHODS
http.STATUS_CODES
http.createServer([options][, requestListener])
http.get(options[, callback])
http.get(url[, options][, callback])
http.globalAgent
http.maxHeaderSize
http.request(options[, callback])
http.request(url[, options][, callback])
http.validateHeaderName(name[, label])
http.validateHeaderValue(name, value)
http.setMaxIdleHTTPParsers(max)

Class: http.Agent

It is good practice, to destroy() an Agent instance when it is no longer in use, because unused sockets consume OS resources.

new Agent([options])
agent.createConnection(options[, callback])
agent.keepSocketAlive(socket)
agent.reuseSocket(socket, request)
agent.destroy()
agent.freeSockets
agent.getName([options])
agent.maxFreeSockets
agent.maxSockets
agent.maxTotalSockets
agent.requests
agent.sockets

Class: http.ClientRequest

Extends: <http.OutgoingMessage>
This object is created internally and returned from http.request(). It represents an in-progress request whose header has already been queued. The header is still mutable using the setHeader(name, value), getHeader(name), removeHeader(name) API. The actual header will be sent along with the first data chunk or when calling request.end().

To get the response, add a listener for 'response' to the request object. 'response' will be emitted from the request object when the response headers have been received. The 'response' event is executed with one argument which is an instance of http.IncomingMessage.

During the 'response' event, one can add listeners to the response object; particularly to listen for the 'data' event.

If no 'response' handler is added, then the response will be entirely discarded. However, if a 'response' event handler is added, then the data from the response object must be consumed, either by calling response.read() whenever there is a 'readable' event, or by adding a 'data' handler, or by calling the .resume() method. Until the data is consumed, the 'end' event will not fire. Also, until the data is read it will consume memory that can eventually lead to a 'process out of memory' error.

For backward compatibility, res will only emit 'error' if there is an 'error' listener registered.

Set Content-Length header to limit the response body size. If response.strictContentLength is set to true, mismatching the Content-Length header value will result in an Error being thrown, identified by code: 'ERR_HTTP_CONTENT_LENGTH_MISMATCH'.

Content-Length value should be in bytes, not characters. Use Buffer.byteLength() to determine the length of the body in bytes.

Event: 'close'
Event: 'connect'
Event: 'continue'
Event: 'finish'
Event: 'information'
Event: 'response'
Event: 'socket'
Event: 'timeout'
Event: 'upgrade'
request.cork()
request.end([data[, encoding]][, callback])
request.destroy([error])
request.destroyed
request.flushHeaders()
request.getHeader(name)
request.getHeaderNames()
request.getHeaders()
request.getRawHeaderNames()
request.hasHeader(name)
request.maxHeadersCount
request.path
request.method
request.host
request.protocol
request.removeHeader(name)
request.reusedSocket
request.setHeader(name, value)
request.setNoDelay([noDelay])
request.setSocketKeepAlive([enable][, initialDelay])
request.setTimeout(timeout[, callback])
request.socket
request.uncork()
request.writableEnded
request.writableFinished
request.write(chunk[, encoding][, callback])

Class: http.Server

Extends: net.Server

Event: 'checkContinue'
Event: 'checkExpectation'
Event: 'clientError'
Event: 'close'
Event: 'connect'
Event: 'connection'
Event: 'dropRequest'
Event: 'request'
Event: 'upgrade'
server.close([callback])
server.closeAllConnections()
server.closeIdleConnections()
server.headersTimeout
server.listen()
server.listening
server.maxHeadersCount
server.requestTimeout
server.setTimeout([msecs][, callback])
server.maxRequestsPerSocket
server.timeout
server.keepAliveTimeout

Class: http.ServerResponse

Extends: <http.OutgoingMessage> This object is created internally by an HTTP server, not by the user. It is passed as the second parameter to the 'request' event.

Event: 'close'
Event: 'finish'

response.addTrailers(headers)
This method adds HTTP trailing headers (a header but at the end of the message) to the response.

Trailers will only be emitted if chunked encoding is used for the response; if it is not (e.g. if the request was HTTP/1.0), they will be silently discarded.

response.cork()
response.end([data[, encoding]][, callback])
This method signals to the server that all of the response headers and body have been sent; that server should consider this message complete. The method, response.end(), MUST be called on each response.

If data is specified, it is similar in effect to calling response.write(data, encoding) followed by response.end(callback).

If callback is specified, it will be called when the response stream is finished.

response.flushHeaders()
response.getHeader(name)
response.getHeaderNames()
response.getHeaders()
response.hasHeader(name)
response.headersSent
response.removeHeader(name)
response.req
response.sendDate
response.setHeader(name, value)
response.setTimeout(msecs[, callback])
response.socket
response.statusCode
response.statusMessage
response.strictContentLength
response.uncork()
response.writableEnded
response.writableFinished
response.write(chunk[, encoding][, callback])
response.writeContinue()
response.writeEarlyHints(hints[, callback])
response.writeHead(statusCode[, statusMessage][, headers])
response.writeProcessing()

Class: http.IncomingMessage

Extends: stream.Readable
An IncomingMessage object is created by http.Server or http.ClientRequest and passed as the first argument to the 'request' and 'response' event respectively. It may be used to access response status, headers, and data.

Different from its socket value which is a subclass of <stream.Duplex>, the IncomingMessage itself extends <stream.Readable> and is created separately to parse and emit the incoming HTTP headers and payload, as the underlying socket may be reused multiple times in case of keep-alive.

Event: 'close'
message.complete
message.destroy([error])
message.headers
message.headersDistinct
message.httpVersion
message.method
message.rawHeaders
message.rawTrailers
message.setTimeout(msecs[, callback])
message.socket
message.statusCode
message.statusMessage
message.trailers
message.trailersDistinct
message.url

Class: http.OutgoingMessage

Extends: Stream
This class serves as the parent class of http.ClientRequest and http.ServerResponse. It is an abstract outgoing message from the perspective of the participants of an HTTP transaction.

Event: 'drain'
Event: 'finish'
Event: 'prefinish'
outgoingMessage.addTrailers(headers)
outgoingMessage.appendHeader(name, value)
outgoingMessage.cork()
outgoingMessage.destroy([error])
outgoingMessage.end(chunk[, encoding][, callback])
outgoingMessage.flushHeaders()
outgoingMessage.getHeader(name)
outgoingMessage.getHeaderNames()
outgoingMessage.getHeaders()
outgoingMessage.hasHeader(name)
outgoingMessage.headersSent
outgoingMessage.pipe()
outgoingMessage.removeHeader(name)
outgoingMessage.setHeader(name, value)
outgoingMessage.setHeaders(headers)
outgoingMessage.setTimeout(msesc[, callback])
outgoingMessage.socket
outgoingMessage.uncork()
outgoingMessage.writableCorked
outgoingMessage.writableEnded
outgoingMessage.writableFinished
outgoingMessage.writableHighWaterMark
outgoingMessage.writableLength
outgoingMessage.writableObjectMode
outgoingMessage.write(chunk[, encoding][, callback])

core_modules's People

Watchers

Dale Corns avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.