skip to content

Flutter auto hot reload using nodejs

/ 1 min read

const fs = require('fs');
const { spawn } = require('child_process');

const currentDirectory = __dirname; // Gets the current directory where the script is located
const flutterCommand = 'flutter'; // Command to run Flutter commands
const flutterArgs = ['run']; // Arguments to run Flutter application

console.log('Starting Flutter application...');
let flutterProcess = spawn(flutterCommand, flutterArgs);

// Output of flutterProcess.stdout
flutterProcess.stdout.on('data', (data) => {
    process.stdout.write(data); // Forward Flutter process stdout data
});

// Handle stderr (if needed)
flutterProcess.stderr.on('data', (data) => {
    console.error(`stderr: ${data}`);
});

// Handle process exit
flutterProcess.on('exit', (code, signal) => {
    console.log(
        `Flutter process exited with code ${code} and signal ${signal}`
    );
});

// Watch current directory for changes
console.log('Watching for changes in', currentDirectory);
let updating = false;
fs.watch(currentDirectory+"/lib", { recursive: true }, (eventType, filename) => {
    if (updating == false) {
        updating = true;
        setTimeout(() => {
            flutterProcess.stdin.write('r');
            updating = false;
        }, 40); // Wait, so it does not reload quicly
    }
});