File System
Performing file system operations
nx.js provides various functions for performing file system operations in your nx.js app. Since there is no universally agreed upon API by the current leading JavaScript runtimes, nx.js implements its own file system APIs which take inspiration from other runtimes.
Some key differences compared to what you might be used to in Node.js:
- Read functions (
Switch.readFile()
,Switch.stat()
, etc.) returnnull
if a given path does not exist (they do not throw an error uponENOENT
). - Write functions (
Switch.writeFileSync()
), will recursively create parent directories as needed, so manually creating directories is rarely necessary.
Switch.FsFile
Switch.FsFile
is a special implementation
of the web File
class, which interacts with the system's physical
file system. As such, it offers a convenient API for working with existing files, and also
for writing files.
Use the Switch.file()
function to create
instances of Switch.FsFile
.
Read as JSON
Reading and parsing a JSON file is a one-liner via the json()
function:
Readable stream
To read a file using the Web Streams API, invoke the stream()
function which returns a ReadableStream
instance:
Writable stream
Switch.FsFile
may also be used to write files using the web WritableStream API, by accessing the
writable
property which contains a WritableStream instance:
If the file path provided to Switch.file()
does not yet exist, then a new file will be created
(as well as any necessary parent directories).
Big files
If you need to write a file larger than 4gb, your application can create a
"big file" by passing the bigFile: true
option to Switch.file()
:
This works even on FAT32 partitions, which normally have a 4gb limit.
How "big files" work under the hood is that a directory is created with the "archive" bit set, which causes the directory to be treated as a file containing the directory's concatenated contents. This is all handled transparently by the operating system, so your application code can treat it as if it were a normal file.