Question: Can anybody give some sample code to read and write a file using JavaScript?

Answer: 
For completeness, the OP does not state he is looking to do this in a browser (if he is, as has been stated, it is generally not possible)

However javascript per se does allow this; it can be done with server side javascript.

See this [documentation on the Javascript File class](http://docs.sun.com/source/816-6411-10/misc.htm#1017481)

**Edit**: That link was to the Sun docs that now have been moved by Oracle.

To keep up with the times here's the node.js documentation for the FileSystem class: <http://nodejs.org/docs/latest/api/fs.html>

**Edit(2)**: You can read files client side now with HTML5: <http://www.html5rocks.com/en/tutorials/file/dndfiles/>
Here is write solution for chrome v52+ (user still need to select a destination doe...)  

source: [StreamSaver.js](https://github.com/jimmywarting/StreamSaver.js/)

```html
<!-- load StreamSaver.js before streams polyfill to detect support -->
<script src="StreamSaver.js"></script>
<script src="https://wzrd.in/standalone/web-streams-polyfill@latest"></script>

```

```js
const writeStream = streamSaver.createWriteStream('filename.txt')
const encoder = new TextEncoder
let data = 'a'.repeat(1024)
let uint8array = encoder.encode(data + "\n\n")

writeStream.write(uint8array) // must be uInt8array
writeStream.close()

```

Best suited for writing large data generated on client side.  
Otherwise I suggest using [FileSaver.js](https://github.com/eligrey/FileSaver.js) to save Blob/Files