Open a File in JavaScript: Node.js and Browser Techniques
Learn how to open a file in JavaScript across Node.js and browser contexts, with practical, runnable examples using fs.readFile, FileReader, and the File System Access API.

Open a file in JavaScript means accessing the contents of a file from disk or a user-provided selection, using Node.js APIs or browser File APIs. In Node.js, you typically read files with fs.readFile or fs.promises.readFile. In the browser, you read user-selected files via FileReader or the modern File System Access API, with careful attention to encoding and security.
Contexts for opening a file in JavaScript
Open a file in JavaScript can mean different things depending on where your code runs. On the server (Node.js), you access the filesystem using built-in modules like fs. In the browser, you cannot access arbitrary disk files due to security, but you can read user-selected files via an input element, FileReader, or the experimental File System Access API. This section sets the stage for concrete examples in Node.js and browser environments.
// Node.js context will be used later in this article
const path = require('path');
console.log(path.resolve('./data/sample.txt'));The key is to understand scope: server-side file access vs. client-side file inputs. This article covers both approaches and compares when to use which, always prioritizing secure handling of user data and proper encoding.
codeExamplesInSection1AllowedForBlockThereIsOne
Steps
Estimated time: 45-60 minutes
- 1
Decide environment
Determine whether you’ll read files on the server with Node.js or on the client with browser APIs. This choice governs which APIs you’ll use and which security considerations matter.
Tip: Start with a small read to verify permissions and encodings. - 2
Set up a simple project
Create a folder, initialize npm if needed, and add a sample.txt to read. This gives you a predictable test target for both Node.js and browser examples.
Tip: Keep sample files in a dedicated test-data directory. - 3
Implement Node.js file read
Write a small script using fs.promises.readFile and run it with Node.js to ensure you can access the filesystem from the server side.
Tip: Prefer promises + async/await for readability. - 4
Implement browser file read (FileReader)
Create a basic HTML page with an input[type=file], then read the chosen file using FileReader. This demonstrates client-side file access securely.
Tip: Always verify file presence before reading. - 5
Add File System Access API sample
Optionally implement a picker to read files directly with showOpenFilePicker, including feature detection and error handling.
Tip: Feature-detect before using experimental APIs. - 6
Handle encoding and errors
Specify encoding (e.g., utf8) when reading text and wrap calls in try/catch blocks to surface meaningful errors.
Tip: Avoid silent failures; surface actionable messages.
Prerequisites
Required
- Required
- Basic command line knowledgeRequired
- Required
Optional
- A modern browser (Chrome/Edge/Firefox) with File System Access API supportOptional
- Optional: Familiarity with async/await and try/catch patternsOptional
Commands
| Action | Command |
|---|---|
| Run a Node.js script that reads a fileReplace with the actual script path that uses fs.readFile or fs.promises.readFile | node path/to/script.js |
| Quick one-liner to read a file with Node.jsRun a quick script that reads a text file in Node.js | node -e 'const fs = require("fs"); fs.readFile("path/to/file.txt", "utf8", (err, data) => { if (err) throw err; console.log(data); });' |
Questions & Answers
What is the File System Access API and when should I use it?
The File System Access API lets web apps read and write local files more directly, after user consent. Use it when you need richer file interactions beyond the FileReader API, but always check for browser support and provide fallbacks.
The File System Access API is a newer browser capability for direct file access, usable after user permission. It’s great for apps that work with local files but only on supported browsers.
Is reading local files in the browser secure?
Browser-based file access is restricted to user-selected files, and your code cannot access arbitrary disk locations. Always validate file types and sizes, and avoid leaking file content to third parties.
Yes, as long as you read only what the user selects and implement proper validations.
Should I use FileReader or File System Access API?
Use FileReader for broad compatibility and simple cases. Use File System Access API when you need more direct, interactive file handling and your target browsers support it.
Start with FileReader for compatibility, switch to FS Access API if you need richer interactions and your audience has compatible browsers.
How do I handle encoding when reading text files?
Specify the encoding (e.g., utf8) in read operations to ensure correct text interpretation. Without encoding, you may get a Buffer or garbled text.
Always set encoding to avoid surprises like unreadable characters.
Can I read files synchronously in Node.js?
Node.js supports synchronous file reads (fs.readFileSync), but it's discouraged in server apps because it blocks the event loop. Prefer asynchronous patterns with fs.promises or callbacks.
Avoid blocking reads in production servers; use async style.
What to Remember
- Open files in Node.js with fs.readFile or fs.promises.readFile
- Browser file access relies on FileReader or the File System Access API
- Always specify encoding for text files to get strings, not buffers
- Use streaming for large files to optimize memory usage
- Handle errors gracefully with try/catch and user-friendly messages