Lesson 2 of 28 · javascript
Using Node.js APIs in the Main Process
Duration: 9 mins
Using Node.js APIs in the Main Process
Because the main process runs plain Node, you can require any built‑in or third‑party module.
Example: File system access
const fs = require('fs').promises;
async function readConfig(){
const data = await fs.readFile(path.join(app.getPath('userData'), 'config.json'), 'utf‑8');
return JSON.parse(data);
}
Example: Child processes
const { exec } = require('child_process');
exec('git --version', (err, stdout) => {
if (err) return console.error(err);
console.log('Git version:', stdout.trim());
});
Example: Native modules
Install a library that needs compilation (e.g., sharp for image processing) and use it directly in the main process.
const sharp = require('sharp');
sharp('input.png').resize(200).toFile('output.png');
Remember: Never expose these Node APIs directly to the renderer – always go through a preload bridge.