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.
var fileSystem = require('fs');
var textToWrite = 'The easiest
way to read the entire contents of a file is with fs.readFile,
fs.readFile(file, [encoding], [callback]); encoding is an optional parameter
that specifies the type of encoding to read the file. Possible encodings are
\'ascii\', \'utf8\', and \'base64\'';
textToWrite = textToWrite + '. 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.';
fileSystem.writeFile(__dirname
+ '/HowToRead.txt', textToWrite, function (error) {
if (error) {
console.log('Error writing file!!!' +
error);
}
});
fileSystem.readFile(__dirname
+ '/SampleText.txt', 'utf8',
function (error, data) {
if (error) {
console.log('Error reading file!!!' +
error);
}
console.log(data);
});
No comments:
Post a Comment