In Electron applications, handling data storage and retrieval can be achieved through various methods, primarily depending on the application's requirements and scale. Here are some mainstream approaches:
1. Local File System
Electron applications can directly access the local file system, which simplifies storing data using JSON, XML, or other formats. For instance, you can utilize the Node.js fs module to read and write files.
javascriptconst fs = require('fs'); // Write data fs.writeFile('data.json', JSON.stringify(data), (err) => { if (err) throw err; console.log('Data saved'); }); // Read data fs.readFile('data.json', (err, data) => { if (err) throw err; console.log(JSON.parse(data)); });
This approach is suitable for small or medium-scale applications where data volume is not particularly large and data formats are relatively simple.
2. Embedded Database
For applications requiring more complex data handling or higher data read/write efficiency, embedded databases such as SQLite or NeDB can be used. These databases offer more features than simple file storage, including transactions, indexing, and query optimization.
javascriptconst sqlite3 = require('sqlite3').verbose(); let db = new sqlite3.Database('./mydb.db'); db.serialize(() => { db.run("CREATE TABLE if not exists user (id INT, name TEXT)"); var stmt = db.prepare("INSERT INTO user VALUES (?, ?)"); for (var i = 0; i < 10; i++) { stmt.run(i, `Name${i}`); } stmt.finalize(); db.each("SELECT id, name FROM user", (err, row) => { console.log(row.id + ": " + row.name); }); }); db.close();
3. Using Mainstream Databases
If data requirements are very high, Electron applications can connect to mainstream database servers via the network, such as MySQL, MongoDB, or PostgreSQL. This typically involves making network requests between the client and server.
javascriptconst { MongoClient } = require('mongodb'); const url = 'mongodb://localhost:27017'; const dbName = 'myproject'; const client = new MongoClient(url); async function run() { try { await client.connect(); console.log("Connected correctly to server"); const db = client.db(dbName); const collection = db.collection('documents'); // Insert data const insertResult = await collection.insertMany([{ a: 1 }, { a: 2 }, { a: 3 }]); console.log('Inserted documents:', insertResult.insertedCount); // Retrieve data const findResult = await collection.find({}).toArray(); console.log('Found documents:', findResult); } finally { await client.close(); } } run().catch(console.dir);
Each of these methods has its own scenarios and pros and cons. In actual development, the appropriate data storage solution should be chosen based on specific application requirements and expected user volume.