How to Read and Write Files in Node.js with Promises

🚀 Reading & Writing Files in Node.js — The Modern Way If you’re still juggling callbacks or fs methods in Node.js, it’s time to move to the cleaner, promise-based API — fs/promises. Using readFile() and writeFile() with async/await makes file operations non-blocking, clean, and easy to handle — perfect for high-concurrency Node.js environments. Here’s the gist 👇 ```📖 Reading a file``` import { readFile } from 'node:fs/promises'; try { const data = await readFile('config.json', 'utf8'); console.log(JSON.parse(data)); } catch (err) { console.error('Error reading file:', err.message); } `````` ```✍️ Writing a file``` import { writeFile } from 'node:fs/promises'; try { const jsonData = JSON.stringify({ name: 'John Doe', email: 'john@example.com' }); await writeFile('user-data.json', jsonData, 'utf8'); console.log('File saved successfully!'); } catch (err) { console.error('Error writing file:', err.message); } `````` 💡 Pro tip: Always wrap file operations in try/catch — errors like ENOENT, EACCES, or JSON parse issues can crash your app if not handled gracefully. Async I/O is one of Node.js’s superpowers — use it well ⚡ #Nodejs #JavaScript #BackendDevelopment #AsyncAwait #WebDevelopment #CodeTips #Programming #WebTechJournals #PublicisSapient #PublicisGroupe #FutureReady #GrowthMindset #ContinuousLearning #LearningTransformation

  • text

To view or add a comment, sign in

Explore content categories