आप क्लाइंट साइड (ब्राउज़र्स) पर JS में फ़ाइलें पढ़ या लिख नहीं सकते। यह सर्वर-साइड Node.js में fs मॉड्यूल का उपयोग करके किया जा सकता है। यह फ़ाइल सिस्टम पर फ़ाइलें पढ़ने और लिखने के लिए सिंक और एसिंक फ़ंक्शन्स प्रदान करता है। आइए Node.js पर fs मॉड्यूल का उपयोग करके फ़ाइलें पढ़ने और लिखने के उदाहरण देखें।
आइए main.js नाम की एक JS फ़ाइल बनाएं जिसमें निम्न कोड हो:
var fs = require("fs"); console.log("Going to write into existing file"); // input.txt नाम की एक नई फ़ाइल खोलें और उसमें Simply Easy Learning! लिखें। fs.writeFile('input.txt', 'Simply Easy Learning!', function(err) { if (err) { return console.error(err); } console.log("Data written successfully!"); console.log("Let's read newly written data"); // नई लिखी गई फ़ाइल पढ़ें और इसकी सभी सामग्री को कंसोल पर प्रिंट करें fs.readFile('input.txt', function (err, data) { if (err) { return console.error(err); } console.log("Asynchronous read: " + data.toString()); }); });
अब परिणाम देखने के लिए main.js चलाएं:
$ node main.js
आउटपुट
Going to write into existing file Data written successfully! Let's read newly written data Asynchronous read: Simply Easy Learning!
आप Node.js में fs मॉड्यूल कैसे काम करता है और इसका उपयोग कैसे करें, इसके बारे में यहां अधिक पढ़ सकते हैं।