nx.js
Concepts

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.) return null if a given path does not exist (they do not throw an error upon ENOENT).
  • 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:

const topScores = await Switch.file('sdmc:/top-scores.json').json();
console.log(topScores);

Readable stream

To read a file using the Web Streams API, invoke the stream() function which returns a ReadableStream instance:

for await (const chunk of Switch.file('sdmc:/data.txt').stream()) {
    console.log(chunk);
}

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:

const file = Switch.file('sdmc:/does-not-yet-exist.txt');
 
const writer = file.writable.getWriter();
await writer.write('write');
await writer.write(' a ');
await writer.write('file ');
await writer.write('incrementally');
await writer.close();

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():

const file = Switch.file('sdmc:/test.txt', {
    bigFile: true
});
 
const writer = file.writable.getWriter();
 
// … write more than 4gb worth of data to the file …
 
await writer.close();

This works even on FAT32 partitions, which normally have a 4gb limit.

Note

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.

On this page