Microsoft Word tool has default privacy settings with disabled macros and Trusted VB scripts set unchecked. So, writing Macros(VB script) to update fields is not a good idea in order to tell users to allow Macros attached to the document file by changing settings.
Open your generated Docx file and press 'alt' + 'F9'. This command will reveal all the field codes. We will be using field code '{NUMPAGES}'(with curly braces) for total number of pages. Note, footer and header are auto updated fields(automatically updates the fields once the document is opened), but for TOC we cannot put it in header or footer. Close the document file.
In your code where you have used xml tags for {NUMPAGES}, set dirty to true, ie.,
var totalPages = '<w:instrText w:instr="TOC" w:dirty="true"> NUMPAGES </w:instrText>
and in Docx Template file, use {@totalPages} to map xml value.
Docx file is actually a zip file, rename the template document file from '.docx' to '.zip'. You will find couple of folders and files in zip. Folder 'word' contains your main document.xml(document file content) and settings.xml(document file settings) files. Open 'settings.xml', and write <w:updateFields w:val="true" />
under <w:settings>
tag make sure you write above code before </w:settings>
. This will ask user to update fields at the time of opening the docx file, this is because we have set updateFields value to true in our 'settings.xml' file. Now save 'settings.xml' and update the zip file (if asked). Rename zip file back to '.docx'. Generate docx file now, it will auto update all the fields.