Skip to content

Corrupted file served if file is changed during serving. #155

@wdanilo

Description

@wdanilo

Hi, I've got such a code for my server:

import path from 'node:path'
import url from 'node:url'
import portfinder from 'portfinder'
import connect from 'connect'
import { WebSocketServer } from 'ws'
import serveStatic from 'serve-static'
import logger from 'morgan'

export const DEFAULT_PORT = 8080

let dirname = path.dirname(url.fileURLToPath(import.meta.url))
// Path of a file that needs to be injected into the bundle for live-reload to work.
export const LIVE_RELOAD_LISTENER_PATH = path.join(dirname, 'live-reload.js')

export async function start({ root, assets, port }) {
    assets = assets ?? path.join(root, 'assets')

    const freePort = await portfinder.getPortPromise({ port: port ?? DEFAULT_PORT })

    const setHeaders = (res) => {
        res.setHeader('Cache-Control', 'no-store')
    }

    const app = connect()
        .use(logger('dev', { skip: (req, res) => res.statusCode < 400 }))
        .use(serveStatic(root, {setHeaders}))
        .use('/assets', serveStatic(assets, {setHeaders}))

    const server = app.listen(freePort)
    const wsServer = new WebSocketServer({ server, clientTracking: true, path: '/live-reload' })

    var serverUrl = `http://localhost:${freePort}`
    console.log('Serving %s', serverUrl)

    return {
        port: freePort,
        reload() {
            wsServer.clients.forEach(sock => sock.send('reload'))
        },
    }
}

And we have observed a very interesting behavior. Namely, when it is serving our WASM file (100MB+), if the WASM is being re-build just when serving starts, then it is served to the browser corrupted. What's interesting is that after it is rebuilt, browser refreshes dont help - the same corrupted file is being served. What helps is restarting the above server to serve non-corrupted file. Does anyone have any idea why this happens and if this can be prevented somehow? I'm OK with serving it in a corrupted state for the first time (during rebuild), but I want the file to be served correctly after page reload.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions