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