Thursday, April 5, 2012

File I/O in Node


The fs module provides both synchronous and asynchronous ways of reading files. The readFile method reads the contents of the file asynchronously.
fs = require('fs');
fs.readFile(file, [encoding], [callback]);

where file is the name of the file to read, encoding is an optional parameter that specifies the type of encoding to read the file. Possible encodings are 'ascii', 'utf8', and 'base64'. If no encoding is provided, the default is utf8.callback is a function to call when the file has been read and the contents are ready - it is passed two arguments, error and data. If there is no error, error will be null and data will contain the file contents; otherwise err contains the error message.
Similarly the writeFile method writes content to a file specified in the function. Read more

No comments: