Node implements File I/O using simple wrappers around standard POSIX functions.
Every method in fs
module have synchronous as well as asynchronous form. Asynchronous methods takes a last parameter as completion function callback and first parameter of the callback function is error. It is preferred to use asynchronous method instead of synchronous method as former never block the program execution where as the second one does.
Read file
// Asynchronous read var fs = require('fs'); fs.readFile(file, [encoding], [callback]);
Examples
// Asynchronous read fs.readFile('/tmp/movies.txt', function (err, data) { if (err) { return console.error(err); } console.log("Data: " + data.toString()); }); // Synchronous read var data = fs.readFileSync('/tmp/movies.txt'); console.log("Data: " + data.toString());
Read JSON file
var fs = require('fs') var dataRaw = fs.readFileSync("/tmp/movies.json") var dataJSON = JSON.parse(dataRaw)
Write file
Writing to a file is another of the basic programming tasks that one usually needs to know about. We can use the handy writeFile
method inside the standard library's fs
module.
var fs = require('fs'); var fs.writeFile(filename, data, [options], [callback])
This method will over-write the file if file already exists. If you want to write into an existing file then you should use another method available.
var fs = require('fs'); fs.writeFile('/tmp/hw.txt', 'Hello World!', function (err) { if (err) return console.log(err); console.log('Wrote!'); });
Write JSON file
var fs = require('fs'); var movie = {title: 'The Shawshank Redemption (1994)', rating: 9.2}; fs.writeFile('/tmp/movie.json', JSON.stringify(movie), function (err) { if (err) return console.log(err); console.log('Wrote!'); });