JavaScript file handling depends on where the code runs. In a browser, your app normally reads files a user selects or drops; it cannot open an arbitrary path on the visitor’s device. In Node.js, the node:fs module can read and write filesystem paths. Use browser File/Blob APIs for user-provided data, Node’s promise-based filesystem methods for ordinary file operations, and streams when data should be processed incrementally.
How to choose a JavaScript file-handling API
| Where the file is | How your code gets access | Usual approach |
|---|---|---|
| In a visitor’s browser | The user selects a file or drops it onto the page | Read the resulting File with a Blob method or FileReader |
| In browser-managed storage | Your app uses origin-private storage, or the user grants access through a supported file-system feature | Use the relevant File System API method after checking browser support and permissions |
| On a Node.js host | Your process supplies a filesystem path or file URL | Use node:fs/promises, or a stream for incremental processing |
| On a web server | Your app requests a resource over HTTP | Use fetch(); cross-origin reads require the server’s CORS permission |
These are different security and access models, not interchangeable APIs. MDN describes browser File and Blob handling separately from filesystem access; Node.js documents path-based operations in node:fs. See MDN’s File API documentation and the Node.js filesystem documentation.
How do I read a file in JavaScript in the browser?
Get a File through a file input
A browser page usually gets local file data only after the user selects or drops it. An <input type="file"> exposes the selected files through its files property, a FileList. Each File is a kind of Blob and includes metadata such as its name, size, MIME type and last-modified date.
<label>Choose a text file
<input id="fileInput" type="file" accept="text/*">
</label>
<pre id="output"></pre>
<script>
const input = document.querySelector('#fileInput');
const output = document.querySelector('#output');
input.addEventListener('change', async () => {
const file = input.files?.[0];
if (!file) return;
output.textContent = `Name: ${file.name}nSize: ${file.size} bytesnType: ${file.type || 'not provided'}`;
try {
output.textContent += `nn${await file.text()}`;
} catch (error) {
output.textContent += `nCould not read file: ${error.message}`;
}
});
</script>
The accept attribute helps guide the file picker; it is not a security check or proof that the file has a particular format. The example reads the file as text. For binary data, use an appropriate Blob method such as arrayBuffer() rather than interpreting arbitrary bytes as text.
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
Read with FileReader when needed
FileReader asynchronously reads a File or Blob and reports completion through events. It remains useful where your target environment or existing code expects its event-based interface. It does not accept a path such as C:UsersNamefile.txt or /home/name/file.txt; the app must first receive a file object through an allowed browser interaction.
function readAsText(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.addEventListener('load', () => resolve(reader.result));
reader.addEventListener('error', () => reject(reader.error));
reader.addEventListener('abort', () => reject(new Error('File read aborted')));
reader.readAsText(file);
});
}
document.querySelector('#fileInput').addEventListener('change', async (event) => {
const file = event.target.files?.[0];
if (!file) return;
try {
document.querySelector('#output').textContent = await readAsText(file);
} catch (error) {
console.error('Unable to read selected file:', error);
}
});
For previews or generated content, an object URL can expose Blob data to browser features that accept URLs. Release URLs created with URL.createObjectURL() using URL.revokeObjectURL() when they are no longer needed. MDN also documents reading Blob data as text or binary and exposing it as a stream. FileReader is available in Web Workers as well as page scripts.
Read a dropped file
Drag-and-drop supplies files through the event’s DataTransfer object. Handle the drop event and use its files list just as you would the input’s list.
const dropZone = document.querySelector('#dropZone');
dropZone.addEventListener('dragover', (event) => event.preventDefault());
dropZone.addEventListener('drop', async (event) => {
event.preventDefault();
const file = event.dataTransfer?.files?.[0];
if (!file) return;
document.querySelector('#output').textContent = await file.text();
});
Give users a visible drop target and a file-input alternative. The code still handles only the file objects supplied by the browser; it does not gain general access to other files on disk.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
Can browser JavaScript read a local file path?
Not through ordinary FileReader or a file input. Browser JavaScript is deliberately not a general-purpose filesystem client: a page cannot silently inspect a visitor’s disk by passing a pathname to a read method. The user must explicitly provide the file.
Browser file-system features are a separate capability. MDN’s File System API documentation describes origin-private file storage and extensions that can access user files with consent. The API is secure-context-only, and support varies by feature and browser. Check support for the exact picker, handle, or writable-stream method your app needs rather than assuming that every method works everywhere. The origin private file system (OPFS) belongs to the site’s origin and is not an ordinary folder visible to the user.
If the file is hosted on a server rather than on the user’s device, request it with fetch(). A cross-origin server must permit the read through CORS for browser JavaScript to access the response.
How do I read a file in Node.js?
Read a suitable whole file with promises
Node.js provides synchronous, callback and promise forms in node:fs. Promise methods suit straightforward asynchronous work. readFile() reads the complete file into memory: without an encoding it returns a Buffer; with an encoding it returns a string.
Recommended Free Tools
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
import { readFile } from 'node:fs/promises';
const path = './notes.txt';
try {
const text = await readFile(path, 'utf8');
console.log(text);
} catch (error) {
console.error(`Could not read ${path}:`, error);
process.exitCode = 1;
}
This example uses ES modules and top-level await. In a CommonJS file, use const { readFile } = require('node:fs/promises'); inside an async function. A relative path resolves from the process’s current working directory, which may differ from the directory containing the script. Use an absolute path or resolve one deliberately if the working directory is not predictable. Filesystem operations can also accept file: URL objects.
Use a stream for incremental processing
A whole-file read holds the complete result in memory. When processing large inputs, or when the task naturally consumes pieces as they arrive, use a readable stream instead. There is no universal file-size cutoff: choose based on the workload, memory budget and processing design.
import { createReadStream } from 'node:fs';
import { createInterface } from 'node:readline';
const lines = createInterface({
input: createReadStream('./large.log', { encoding: 'utf8' }),
crlfDelay: Infinity
});
for await (const line of lines) {
if (line.includes('ERROR')) console.log(line);
}
createReadStream() processes data incrementally; Node also documents readable streams from file handles. Read-stream options can select a byte range. For filehandle.createReadStream(), the documented start and end positions are inclusive.
How do I write or append a file in Node.js?
For a straightforward write, use the promise API’s writeFile(). To add content rather than replace the file’s contents, use appendFile(). These calls are asynchronous and reject if the operation fails.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
import { writeFile, appendFile } from 'node:fs/promises';
await writeFile('./report.txt', 'First linen', 'utf8');
await appendFile('./report.txt', 'Another linen', 'utf8');
Choose a stream-based write when output is produced incrementally, rather than building an entire output string or buffer first. Node’s filesystem API also includes writable streams; use the stream’s completion and error handling as part of the surrounding application. Filesystem details, flags and directory behavior can vary by operating system and filesystem, so do not assume every platform-specific option is portable.
How do I open and close a Node.js file handle safely?
Use open() when you need a handle for multiple operations or stream access. Close it explicitly; Node’s documentation warns against relying on automatic cleanup.
import { open } from 'node:fs/promises';
const file = await open('./notes.txt', 'r');
try {
const text = await file.readFile({ encoding: 'utf8' });
console.log(text);
} finally {
await file.close();
}
The finally block runs whether reading succeeds or throws, preventing a successfully opened handle from being left open after an error. Select flags for the intended operation and check the Node documentation for platform-specific behavior.
FileReader vs. fs: what is the difference?
| Question | Browser FileReader | Node.js filesystem |
|---|---|---|
| Where it runs | Browser page or Web Worker | Node.js process |
| What it reads | A File or Blob already made available to the page |
A path or file URL accessible to the process |
| Permission model | User supplies a file; separate file-system features require consent and supported browser capabilities | Access depends on the host process, path and operating-system permissions |
| Common interaction | Event-driven reads | Promise, callback, synchronous or stream APIs |
| Memory approach | Blob reading or streaming features, depending on the task | readFile() materializes the whole result; streams support incremental work |
Use FileReader when browser code must read a user-provided file and its event interface suits the app. Use Node’s filesystem APIs for files available to a server-side process. Neither API substitutes for the other runtime’s permission model.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Repair Windows errors before they cause bigger problems3Scan for outdated or missing drivers - takes under a minuteBest Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Common file-handling errors and fixes
- No selected file: The input may have no selection, or the user may cancel the picker. Check
files?.[0]before reading. - Trying to pass a local pathname to FileReader: It accepts a
FileorBlob, not an arbitrary path. Ask the user to select or drop the file, or use a supported consent-based file-system feature. - Node reports that a file cannot be found: A relative path resolves from
process.cwd(), not necessarily from the script directory. Log the working directory and verify the resolved path. - Unexpected text or corrupted-looking content: The file may be binary or use a different text encoding. Read bytes as a
BufferorArrayBufferand decode according to the actual format. - Memory use grows during a Node read:
readFile()loads the whole result into memory. Process with a readable stream when incremental handling fits the task. - A browser file-system method is unavailable: Support depends on the exact feature and browser, and the API requires a secure context. Confirm that method’s current support and use a file-input workflow where appropriate.
- Cross-origin fetch is blocked: The remote server must allow the browser origin through CORS. A client-side change cannot grant permission the server has not given.
- A Node operation fails despite valid JavaScript: The path may be inaccessible under the process’s permissions, or behavior may differ by operating system or filesystem. Inspect the error code and verify the path and runtime environment.
Or skip the browser setup
If your goal is a website screenshot rather than reading a local file, ScreenshotNeo offers a one-request API. Its capture can accept cookie or consent banners and remove more than 60 known consent platforms, newsletter popups and chat widgets before capture; those steps can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads and cache hits cost nothing, and responses identify the page verdict and billing status in headers. It also provides an MCP server for AI agents and has a free plan with 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 screenshots. See the ScreenshotNeo website and API documentation.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Sign up free for 1,000 screenshots a month, with no card required.
Performance and reliability considerations
- Keep work asynchronous in Node services: Promise-based filesystem methods avoid blocking the JavaScript thread while the operation completes. Synchronous methods block the event loop and further JavaScript execution, so reserve them for deliberate cases such as simple scripts.
- Match the data strategy to the job: Whole-file reads are convenient when the complete content fits the application’s memory budget. Streams are useful when processing incrementally; neither approach has a universally correct size threshold.
- Handle failure and cleanup: Catch rejected promise operations, check for absent browser selections, and close explicitly opened file handles in a
finallyblock. - Respect runtime boundaries: Browser permissions and Node process permissions are different. A web page’s access to a selected file does not imply that a server can read that device’s path.
Frequently Asked Questions
Is FileReader available in Web Workers?
Yes. MDN documents FileReader as available in Web Workers.
Can a browser read a file from another website with fetch?
It can request a server resource, but cross-origin JavaScript access depends on the server allowing the read through CORS.
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallQuick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

