In Nodejs, you can perform file I/O operations through the FS (file system) module.
API Link Address:
Http://nodeapi.ucdok.com/#/api/fs.html
The following are examples of using FS file systems:
1. Module Invocation declaration:
var fs= require (' FS ');
var path = require (' path ');
FS is the file module, path is the system path module.
2. You can use the WriteFile method to write data to a file folder.
Fs.writefile (filename, data, [options], callback)
FileName Saves the path address for the specific file,
Data is the object to which the file is to be written,
[Options] for the specific save file configuration, encoding format, etc.,
Callback for the specific callback function, the corresponding error capture and prompt.
The code is as follows:
function (Err) { ifthrow err; Console.log ("Export account success!" ); });
Writes data to a file path in JSON format.
3. Use the ReadFile method to read the file data.
Fs.readfile (filename, [options], callback)
FileName is the file path and name,
[Options] are configured for the specific options, including how the data is encoded,
Callback is the callback function, the corresponding error handling and prompt.
The code is as follows:
function (err,bytesread) { ifthrow err; Console.log (bytesread);});
The result is:
read out the data binary stream file, if needed for the specific data, need to encode the configuration, the code is as follows:
Fs.readfile (Path.join (__dirname, ' account.js '),{encoding: ' Utf-8 '}function (err,bytesread) { if Throw err; var data=Json.parse (bytesread); Console.log (data[0]); Console.log ("readFile success") ;
The result is:
4. Read the relevant Ingwenj name under the folder.
Readdir (Path,callback)
Path is a specific read folder path address,
Callback is the callback function.
Readdirsync (path) is the real-time synchronous version method for reading files.
Path is the specific folder path address.
The code is as follows:
var Data=Fs.readdirsync (__dirname); Console.log (data);
The results are as follows:
In this way, a simple example of file writing and reading is realized, and further study is needed for the application in depth.
If you have any errors, please forgive them.
Simple Nodejs File System (FS) Read and write examples.