An Easier way to Read and Write Files in ElectronJS

What's it about?

An easier way to read and write files in ElectronJS

2 min to read
electron
javascript
nodejs
webdev

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