Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
const fs = require('fs'); // --- Callback style (old way) --- fs.readFile('data.txt', 'utf8', (err, data) => { if (err) { console.error('Error:', err); return; } fs.writeFile('output.txt', data.toUpperCase(), (err) => { if (err) console.error(err); else console.log('Done writing'); }); }); // --- Promise style --- function readFileProm(path) { return new Promise((resolve, reject) => { fs.readFile(path, 'utf8', (err, data) => { if (err) reject(err); else resolve(data); }); }); } readFileProm('data.txt') .then(data => data.toUpperCase()) .then(upper => console.log(upper)) .catch(err => console.error('Promise rejected:', err)); // --- Promise.all — run multiple promises in parallel --- const p1 = readFileProm('file1.txt'); const p2 = readFileProm('file2.txt'); Promise.all([p1, p2]) .then(([content1, content2]) => { console.log('Both files loaded'); }) .catch(err => console.error('One failed:', err));
Result
Open