JavaScript - export to file

revision:


Content

JavaScript export function Some practical examples Examples with input/output elements


JavaScript export function

top

The export statement is used when creating JavaScript modules to export live bindings to functions, objects, or primitive values from the module so they can be used by other programs with the import statement.

The value of an imported binding is subject to change in the module that exports it.
When a module updates the value of a binding that it exports, the update will be visible in its imported value.
Exported modules are in strict mode whether you declare them as such or not.
The export statement cannot be used in embedded scripts.

example: export functions as an object

codes:
                <script>
                    function fun1(){}
                    function fun2(){}
                    export{fun1, fun2}

                </script>
            

example: use export statement in front of function definitions

codes:
                <script>
                    export function fun1(){}
                    export function fun2(){}
                </script>
            

Syntax : there are two types of exports: named exports (zero or more exports per module) and default exports (one per module)

Syntax examples:

        / Exporting individual features
        export let name1, name2, …, nameN; // also var, const
        export let name1 = …, name2 = …, …, nameN; // also var, const
        export function functionName(){...}
        export class ClassName {...}

        // Export list
        export { name1, name2, …, nameN };

        // Renaming exports
        export { variable1 as name1, variable2 as name2, …, nameN };

        // Exporting destructured assignments with renaming
        export const { name1, name2: bar } = o;
        export const [ name1, name2 ] = array;

        // Default exports
        export default expression;
        export default function (…) { … } // also class, function*
        export default function name1(…) { … } // also class, function*
        export { name1 as default, … };

        // Aggregating modules
        export * from …; // does not set the default export
        export * as name1 from …; // ECMAScript® 2020
        export { name1, name2, …, nameN } from …;
        export { import1 as name1, import2 as name2, …, nameN } from …;
        export { default, … } from …;
    

named exports syntax:

                // export features declared earlier
                export { myFunction, myVariable };

                // export individual features (can export var, let,
                // const, function, class)
                export let myVariable = Math.sqrt(2);
                export function myFunction() { /* ... */ };
            

default exports syntax:

                // export feature declared earlier as default
                export { myFunction as default };

                // export individual features as default
                export default function () { /* ... */ }
                export default class { .. }

                // each export overwrites the previous one
            

Named exports are useful to export several values.

During the import, it is mandatory to import them within curly braces with the same name of the corresponding object.

But a default export can be imported with any name.

Export to doc file

Generally, the export feature is used to download web page content as a file and save it for offline use.

Microsoft Word or Doc (.doc) format is ideal for exporting HTML content in a file.

The export to doc functionality can be easily implemented on the web application without server-side interaction.
There is a client-side solution to export HTML to word document using JavaScript.

The client-side export to doc functionality makes the web application user-friendly.
The user can export a specific part of the web page content without page refresh

The Export2Word() function converts HTML content to word or export specific part of a web page with images, and download as Doc file (.doc).

element: required; specify the element ID to export content from.
filename: optional; specify the file name of the word document.

Wrap the HTML content in a container you want to export to MS Word document (.doc).

example

        <div id="exportContent">
            <!-- the content here -->
        </div>    
    

Trigger Export2Word() function to export HTML content as .doc file using JavaScript.

example

        <button onclick="Export2Word('exportContent');">Export as .doc</button>
    

If you want to export HTML with a custom file name, pass your desired file name in the Export2Word() function.

example

        <button onclick="Export2Word('exportContent', 'word-content');">Export as .doc</button>
    

By default, the word file will be saved as a .doc file. If you want to export word file as a .docx file, specify the extension in the file name.

example

        <button onclick="Export2Word('exportContent', 'word-content.docx');">Export as .docx</button>
    

Some practical examples

top
example: export variables or arrow functions

export multiple variables

codes:
                    <script>
                        export const firstName = "Alice";
                        export const lastName = "Waelbers";
                    </script>
                

export arrow functions

codes:
                    <script>
                        export const sum = (x,y) => x + y;
                        export const sub = (x,y) => x - y;
                        export const mul = (x,y) => x * y;
                        export const div = (x,y) => x / y;

                    </script>
                

example: export or import multiple functions

example: export multiple functions

codes:
                    <script>
                        export function exampleFunctionOne(){
                            console.log('hello, world');
                        }
                        export function exampleFunctionTwo(){
                            console.log("exporting multiple functions from a module!");
                        }
                        export function exampleFunctionThree(){
                            console.log("JavaScript is awesome");
                        }
                    </script>
                    <script>
                        export default function myDefaultFunction(){}
                        export function namedExporTExample(){}
                        export function namedExportExampleTwo(){}
                    </script>
                

example: import multiple functions

codes:
                    <script>
                        import{fun1, fun2} from "./example"; //.js extension not needed in file path
                        import{exampleFunctionOne, exampleFunctionTwo} from ".some-js-file";
                    </script>
                    <script>
                        import myDefaultFunction, {
                            namedExportExample,
                            namedExportExampleTwo,
                        } from ".sone-js-file";
                    </script>
                

example: default export and import, export anything

example: default export and import

codes:
                    <script>
                        export default function(){
                            console.log("hello from example.js");
                        }
                        import example from "example";
                        example();  //prints "hello from example.js"
                    </script>
                

example: export anything....

codes:
                    <script>
                        //example.js
                        export const user = 'John';
                        export let days = ['Monday', 'Tuesday', 'Wedneasday'];
                        export var countries = ['Belgium', 'Netherlands', 'Germany'];
                        export function sayHi(){
                            console.log("hello, world!")
                        }
                        export const greet = name =>{
                            console.log("hello" + name +'!');
                        }
                        export class User{
                            constructor(username){
                                this.username = username
                            }
                        } 
                    </script>
                

example: multiple exports, generate file and download it

example: multiple exports in a separate line

                    <script>
                            const user = "John";
                            let days = ['Monday', 'Tuesday', 'Wednesday'];
                            var countries = ['Belgium', 'Netherlands', 'Germany'];
                            function sayHi(){
                                console.log('hello, world!!');
                            }
                            const greet = name =>{
                                console.log('hello' + name + '!');
                            }
                            class User{
                                constructor(username){
                                    this.username = username
                                }
                            }
                            export{user, days, countries, sayHi, greet, Use}
                    </script> 
                

example: generate a file (with any extension) and download it without contact any server

                    <script>
                        var content = "What's up , hello world";
                        // any kind of extension (.txt,.cpp,.cs,.bat)
                        var filename = "hello.txt";
                        var blob = new Blob([content], {
                        type: "text/plain;charset=utf-8"
                        });
                        saveAs(blob, filename);
                    </script>
                    <script src="js/FileSaver.js"></script>
                    <script>
                        function saveDynamicDataToFile() {
                            var userInput = document.getElementById("myText").value;
                            var blob = new Blob([userInput], { type: "text/plain;charset=utf-8" });
                            saveAs(blob, "dynamic.txt");
                        }
                    </script>
                

example: export all functions, export HTML

example: export all functions from a file

                    <script>
                        export const foo = () => {
                        // ...
                        };
                        export const bar = () => {
                        // ...
                        };
                        export const baz = (value) => {
                        // ...
                        };
                    </script>
                

example: export HTML to MS Word

codes:
                    <div id="content-to-pdf">
                        <h3>Best ways to loose weight</h3>
                        <p>The best way to loose weight is just contol your diet. </p>
                        <a href="">Read this nice article here</a>
                    </div>
                    <button onclick="Export2Doc('content-to-pdf');">Export as .doc</button>
                    <script type="text/javascript">
                        function Export2Doc(element, filename = ''){
                            var html = "<html xmlns:o='urn:schemas-microsoft-com:office:office'
                            xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://
                            www.w3.org
                            /TR/REC-html40'><
                            head><meta><title>Export HTML To Doc</title></head><body>";
                            var footer = "</body></html>";
                            var html = html+document.getElementById(element).innerHTML+footer;
                            var url = 'data:application/vnd.ms-word;charset=utf-8,' + 
                            encodeURIComponent(html);
                            filename = filename ? filename+'.doc':'document.doc';
                            var downloadLink = document.createElement("a");
                            document.body.appendChild(downloadLink);
                            downloadLink.href = url;
                            downloadLink.download = filename;
                            downloadLink.click();
                            document.body.removeChild(downloadLink);
                        }
                    </script>
                

example: export HTML to PDF

example: export HTML table to PDF file

codes:
                <style type="text/css">
                    body{font-family: Arial; font-size: 10pt;}
                    table{border: 1px solid #ccc; border-collapse: collapse;}
                    table th{background-color: #F7F7F7; color: #333; font-weight: bold;}
                    table th, table td{ padding: 5px; border: 1px solid #ccc;}
                </style>
                <table id="tblCustomers" cellspacing="0" cellpadding="0">
                    <tr>
                        <th>Customer Id</th>
                        <th>Name</th>
                        <th>Country</th>
                    </tr>
                    <tr>
                        <td>1</td>
                        <td>John Hammond</td>
                        <td>United States</td>
                    </tr>
                    <tr>
                        <td>2</td>
                        <td>Mudassar Khan</td>
                        <td>India</td>
                    </tr>
                    <tr>
                        <td>3</td>
                        <td>Suzanne Mathews</td>
                        <td>France</td>
                    </tr>
                    <tr>
                        <td>4</td>
                        <td>Robert Schidner</td>
                        <td>Russia</td>
                    </tr>
                </table>
                <br />
                <input type="button" id="btnExport" value="Export" onclick="Export()" />
                <script type="text/javascript" src="https://cdnjs.cloudflare.com
                /ajax/libs/pdfmake/0.1.22/pdfmake.min.js"></script>
                <script type="text/javascript" src="https://cdnjs.cloudflare.com
                /ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
                <script type="text/javascript">
                    function Export() {
                        html2canvas(document.getElementById('tblCustomers'), {
                            onrendered: function (canvas) {
                                var data = canvas.toDataURL();
                                var docDefinition = {
                                    content: [{
                                        image: data,
                                        width: 500
                                    }]
                                };
                                pdfMake.createPdf(docDefinition).download("Table.pdf");
                            }
                        });
                    }
                </script>
            


Examples with input/output elements

top
example: save to file.
Text to save:
Filename to save as:
Select a file to load:
codes:
                <table>
                    <tr><td>Text to save:</td></tr>
                    <tr>
                        <td colspan="3"><textarea id="inputTextToSave" cols="80" rows="25"></textarea></td>
                    </tr>
                    <tr><td>Filename to save as:</td>
                        <td><input id="inputFileNameToSaveAs" placeholder="file name"></td>
                        <td><button onclick="saveTextAsFile()">Save text to File</button></td>
                    </tr>
                    <tr>
                        <td>Select a file to load:</td>
                        <td><input type="file" id="fileToLoad"></td>
                        <td><button onclick="loadFileAsText()">Load selected file</button><td>
                    </tr>
                </table>
                    <script type="text/javascript">
                        function saveTextAsFile(){
                            var textToSave = document.getElementById("inputTextToSave").value;
                            var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"});
                            var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
                            var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
                        
                            var downloadLink = document.createElement("a");
                            downloadLink.download = fileNameToSaveAs;
                            downloadLink.innerHTML = "Download File";
                            downloadLink.href = textToSaveAsURL;
                            downloadLink.onclick = destroyClickedElement;
                            downloadLink.style.display = "none";
                            document.body.appendChild(downloadLink);
                        
                            downloadLink.click();
                        }
                        
                        function destroyClickedElement(event){
                            document.body.removeChild(event.target);
                        }
                        
                        function loadFileAsText(){
                            var fileToLoad = document.getElementById("fileToLoad").files[0];
                            var fileReader = new FileReader();
                            fileReader.onload = function(fileLoadedEvent){
                                var textFromFileLoaded = fileLoadedEvent.target.result;
                                document.getElementById("inputTextToSave").value = textFromFileLoaded;
                            };
                            fileReader.readAsText(fileToLoad, "UTF-8");
                        }
                </script>        
            

example: save in text file
Save project in txt file

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam luctus facilisis ante id luctus.
Aliquam vestibulum, dui in pulvinar facilisis, felis nisl viverra nisl,
nec ultrices neque tortor eget erat. Vivamus vel leo vehicula, condimentum quam
aliquam, congue mauris. Pellentesque id lectus id nulla molestie vehicula sed at velit.
Maecenas sit amet tristique nunc, in lobortis mi. Integer in turpis odio. Duis eget urna
vestibulum, venenatis justo et, semper neque. Suspendisse in ante massa. Aenean massa
nisl, tincidunt id nisl eu, convallis lobortis augue. Integer blandit augue eget nunc
condimentum consectetur. Duis gravida nisl hendrerit, sagittis orci in, sollicitudin risus. Nullam
elementum sem nec nunc facilisis, et semper metus tincidunt.
Phasellus ornare quis ipsum non scelerisque. In sollicitudin est placerat nibh porttitor pretium.
Phasellus ac purus nulla. Phasellus in enim vel leo viverra sodales eget sit amet ante. Sed
ultrices elementum nibh, tristique euismod nunc volutpat sit amet. Suspendisse potenti. Morbi
feugiat diam tristique, euismod dui in, mattis diam. Vestibulum euismod commodo cursus. Proin
posuere libero vitae purus blandit, in posuere erat malesuada. Donec ultrices vel velit in feugiat.
Vestibulum suscipit erat urna, bibendum vestibulum dui varius sit amet.

codes:
                <a id="exportxt" href="#">Save project in txt file</a>
                <div id="editor">
                    <p class="spec">Lorem ipsum dolor sit amet, consectetur 
                    adipiscing elit. .... sit amet.</p>
                </div>
                <style>
                    #editor{display:flex; width:40vw; font-family:Arial, Helvetica,
                        sans-serif;  }
                </style>
                <script type="text/javascript">
                    window.onload = function() {
                    //Get a reference to the link on the page with an id of 
                    "exportxt"
                    var a = document.getElementById("exportxt");
                    //Set code to run when the link is clicked by assigning a 
                    function to "onclick"
                    a.onclick = function() {
                        function downloadInnerHtml(filename, elId, mimeType) {
                            var elHtml = document.getElementById(elId).innerHTML;
                            var link = document.createElement('a');
                            mimeType = mimeType || 'text/plain';
                            link.setAttribute('download', filename);
                            link.setAttribute('href', 'data:' + mimeType  +  ';
                            charset=utf-8,' + encodeURIComponent(elHtml));
                            link.click();
                        }
                        var fileName =  'myexportedhtml.txt'; // You can use the
                        .txt extension if you want
                        downloadInnerHtml(fileName, 'editor','text/plain');
                            return false;
                        }
                    }
                </script>
            

example: save textarea to file
codes:
                <div id="docx">
                    <div class="WordSection1">
                    <textarea placeholder="your comments here" rows="6" cols="55"></textarea>
                    
                    </div>
                </div>
                <button onclick="export2Word(window.docx)">Export</button>
                <script>
                function export2Word( element ) {
                    var html, link, blob, url, css;
                    css = (
                    '<style>' +
                    '@page WordSection1{size: 841.95pt 595.35pt;mso-page-orientation: landscape;}' +
                    'div.WordSection1 {page: WordSection1;}' +
                    '</style>'
                    );
            
                    html = element.innerHTML;
                    blob = new Blob(['\ufeff', css + html], {
                    type: 'application/msword'
                    });
                    url = URL.createObjectURL(blob);
                    link = document.createElement('A');
                    link.href = url;
                    link.download = 'Document';  // default name without extension 
                    document.body.appendChild(link);
                    if (navigator.msSaveOrOpenBlob ) navigator.msSaveOrOpenBlob( blob, 'Document.doc'); // IE10-11
                        else link.click();  // other browsers
                    document.body.removeChild(link);
                    };
                </script> 
            

example: save in Microsoft
A1 B1 C1 E1
A2 B2 C2 E2
A3 B3 C3 E3
A4 B4 C4 E4
Click to open table in Microsoft
codes:
                <div id="docx">
                    <div class="WordSection1">
                    <table>
                        <tr>
                        <td>A1<https://jsfiddle.net/78xa14vz/3/#/td>
                        <td>B1</td>
                        <td>C1</td>
                        <td>E1</td>
                        </tr>
                        <tr>
                        <td>A2</td>
                        <td>B2</td>
                        <td>C2</td>
                        <td>E2</td>
                        </tr>
                        <tr>
                        <td>A3</td>
                        <td>B3</td>
                        <td>C3</td>
                        <td>E3</td>
                        </tr>
                        <tr>
                        <td>A4</td>
                        <td>B4</td>
                        <td>C4</td>
                        <td>E4</td>
                        </tr>
                    </table>
                    </div>
                </div>
                <button id="export">Export</button> Click to open table in Microsoft Word
                <script>
                    window.export.onclick = function() {
                        if (!window.Blob) {
                            alert('Your legacy browser does not support this action.');
                        return;
                        }
                    var html, link, blob, url, css;
                    // EU A4 use: size: 841.95pt 595.35pt;
                    // US Letter use: size:11.0in 8.5in;
                    css = (
                        '<style>' +
                        '@page WordSection1{size: 841.95pt 595.35pt;mso-page-orientation: landscape;}' +
                        'div.WordSection1 {page: WordSection1;}' +
                        'table{border-collapse:collapse;}td{border:1px gray solid;width:5em;padding:2px;}'+
                        '</style>'
                    );
                    
                    html = window.docx.innerHTML;
                    blob = new Blob(['\ufeff', css + html], {
                        type: 'application/msword'
                    });
                    url = URL.createObjectURL(blob);
                    link = document.createElement('A');
                    link.href = url;
                    // Set default file name. 
                    // Word will append file extension - do not add an extension here.
                    link.download = 'Document';   
                    document.body.appendChild(link);
                    if (navigator.msSaveOrOpenBlob ) navigator.msSaveOrOpenBlob( blob, 'Document.doc'); // IE10-11
                            else link.click();  // other browsers
                    document.body.removeChild(link);
                    };
                </script>