Search code examples
javascripthttpserver

http-server net serving the fresh js file


I haven't used http-server npm module before!

i was just getting starting with using service worker by creating an example app using this blog as a source

In this the author have used http-server to demonstrate service worker!

From the blog, I copied the code snippet to check if chrome is supported

const check = () => {
    if (!('serviceWorker' in navigator)) {
      throw new Error('No Service Worker support!')
    }
    if (!('PushManager' in window)) {
      throw new Error('No Push API Support!')
    }
    console.log('Everything works fine')
  }
  const main = () => {
    check()
  }
  main()

Notice the console.log('Everything works fine')

Now, as i proceeded with Article, I changed my main.js as instructed to this

const check = () => {
    if (!('serviceWorker' in navigator)) {
      throw new Error('No Service Worker support!')
    }
    if (!('PushManager' in window)) {
      throw new Error('No Push API Support!')
    }
    console.log(`Browser supports Pushmanager and Service worker`)
  }

  // Async so we can use await 
  const  main = async () => {
    check()
    const swRegistration = await registerServiceWorker();
  }


  //To run service worker we need to first register service worker 
  //Registering Service Worker
  const registerServiceWorker = async () => {
    const swRegistration = await navigator.serviceWorker.register('service.js'); //notice the file name
    return swRegistration;
}

but when I go the page, it keeps logging this from our first code snippet in the console

Everything works fine

I checked the main.js, and it appears the server is still serving the previous main.js instead of new one.

If I go manually to my file and open it without the server, the main.js shows my new code changes.

I have tried turning of the server (using ctrl/cmd + c) and restarting it again but no help.

Can someone help me out in fixing it?


Solution

  • Looks like http-server tells the browser to cache pages for an hour by default:

    -c Set cache time (in seconds) for cache-control max-age header, e.g. -c10 for 10 seconds (defaults to '3600'). To disable caching, use -c-1.

    Restart the server with http-server -c-1, then do a hard refresh in the browser (Ctrl/Cmd+Shift+R in Firefox or Chrome).