An Easier way to Read and Write Files in ElectronJS
An easier way to read and write files in ElectronJS
Tags
TLDR 🥱!!!
On the main thread or process, use ExpressJs along with simple NodeJs apis (like fs
and path
) to read and write files. Easy Peasy! 😊
But to learn how to do it, keep reading. 👇🏻
Dependencies that you’ll need 📝
Setting up ExpressJs ☕
You know that index.js
or that index.ts
file you have in your electron project,
that contains the code to create the main window and all that?
One way to identify that is that it’ll for sure have a function called createWindow
inside it.
Find that file and call your ExpressJs server in it. I do it at the top, right after the imports.
const expressApp = startServer(); expressApp.listen(8000, () => console.log('express app listening on port 8000'));
That’s about it! Honestly 😅, couldn’t get any more easy, right?
You can now use fs
and path
modules to read and write files.
- 🥰 A tip for ya 👇🏻
An effective 💪🏻 and awesome ⭐ way to read files is through using a simple file search algorithm that I’ve wrote about earlier. Check it out over here
And 😒
Just for the sake of it, here’s how you can read files :-
- The
startServer
function.
export default function startServer() { const expressApp = express(); expressApp.use(cors()); expressApp.get(`/`, (_, res) => { res.statusCode = 200; res.contentType('text/plain'); res.send( `Server is up and running. Requst files from /files/{fileName}` ); }); expressApp.use('/files', fileRouter); return expressApp; }
- And here’s the
fileRouter
from above
const router = express.Router(); router.get('/:filename', (req, res) => { const filename = req.params.filename; // 👇🏻 find this `fileSearch` algorithm in Related Posts dropdown fileSearch( pathOfDirectoryToSearchIn, filename, (err: Error, resultArr: string[]) => { if (err) { res.statusCode = 500; res.contentType('text/plain'); res.send(err); } else { res.statusCode = 200; // 👇🏻 or 'application/json' or whatever based on data type res.contentType('text/plain'); resultArr.length > 0 ? res.sendFile(resultArr[0]) : res.send('No file found'); } }); });
That’s it!, thanks 🤗 for reading all the way till down here