Download source of webpage to file with Javascript and grunt

I have a problem and question with my task. I wrote some app in GruntJs. I have to download source of web-page by gruntJs.

For example I have a page: example.com/index.html.

I would like to give URL in Grunt task, like this: scr: "example.com/index.html".

And then, I have to have this source in file, ex: source.txt.

How can i do this?

There are a couple approaches to this.

First is the raw http.get from the node.js API as mentioned in the comments. This will get you the raw source as served up by the initial load of the page. The problem comes when that site makes extensive use of javascript to build further html after ajax requests.

Second approach is to use an actual browser engine to load the site and execute whatever javascript & further HTML building runs on page load. The most common engine for this is PhantomJS and it's wrapped in a Grunt library called grunt-lib-phantomjs.

Fortunately, someone has provided another layer on top of that to do almost exactly what you're asking for: https://github.com/cburgdorf/grunt-html-snapshot

The example config from the link above:

grunt.initConfig({
    htmlSnapshot: {
        all: {
          options: {
            //that's the path where the snapshots should be placed
            //it's empty by default which means they will go into the directory
            //where your Gruntfile.js is placed
            snapshotPath: 'snapshots/',
            //This should be either the base path to your index.html file
            //or your base URL. Currently the task does not use it's own
            //webserver. So if your site needs a webserver to be fully
            //functional configure it here.
            sitePath: 'http://localhost:8888/my-website/',
            //you can choose a prefix for your snapshots
            //by default it's 'snapshot_'
            fileNamePrefix: 'sp_',
            //by default the task waits 500ms before fetching the html.
            //this is to give the page enough time to to assemble itself.
            //if your page needs more time, tweak here.
            msWaitForPages: 1000,
            //if you would rather not keep the script tags in the html snapshots
            //set `removeScripts` to true. It's false by default
            removeScripts: true,
            //he goes the list of all urls that should be fetched
            urls: [
              '',
              '#!/en-gb/showcase'
            ]
          }
        }
    }
});