File I/O operations in Nodejs through the FS (file system) module
var fs = require (FS ");//fs as file module
var path = require (' path ');//path as System path module
1. You can use the WriteFile method to write data to a file under a folder
Fs.writefile (Filename,data,[option],callback)
FileName Saves the path address for the specific file
Data is written to a specific file object
[option] For specific save file configuration, encoding format, etc.
Callback callback function
Fs.writefile (Path.join (__dirname, ' account.js '), Json.stringify (Tempaccount), function (err) { if (err) throw err; Console.log ("Export account success!"); /writes data to a file path in JSON format.
2. Read the data ReadFile
Fs.readfile (Filename,[options],callback)
FileName Folder path and name
[option] for specific configuration items and encoding formats
Callback Callback
Fs.readfile (Path.join (__dirname, ' account.js '), function (err,bytesread) { if (err) throw err; Console.log (bytesread);}); /read-out data binary stream file
If you need to read the specific data, you need to encode the following configuration:
Fs.readfile (Path.join (_dirname, ' a.js '), {encoding: ' Utf-8 '},function (err) {})
3. Read the folder under Fs.readdir (Path,callback);
Fs.readdir (path,callback);
Path is the specific read folder path address
Callback Callback
Fs.readdirsync (path) is a real-time synchronous version method for reading files
Path is specific to the folder paths
4. Other common file operations
Determine if a file exists
Fs.exists (file path, callback (ERR,FD));
Renaming
Fs.rename (old filename, new file name, callback function);
File owner Change
Fs.chown (filename, uid,gid,callback);
Fs.fchown (file handle Fd,uid,gid, callback);
Fs.lchown (link path, Uid,gid, callback);
File permission changes
Fs.chmod (file name, mode, callback)
Fsfchmod (file handle, mode, callback)
Fslchmod (link path, mode, callback)
File information
Fs.stat (file path, callback function);
Fs.fstat (file handle, callback function);
Fs.lstat (link path, callback function);
File time
Fs.utimes (file path, access time, new time, callback);
Fs.futimes (file handle, access time, new time, callback);
Monitoring files
Fs.watchfile (file name, [Option],listener_callback (stats of the current file, stats before change));
Fs.unwatchfile (file name);
Directory Operations
Fs.mkdir (path, permission, callback);
Fs.rmdir (path, callback);
Fs.readdir (path, callback);
Create a link
Fs.link (Srcpath,dstpath,[callback])
Fs.symlink ();
Read the path that the link points to
Fs.readlink (Path,[callback])
Fs.unlink (Path,[callback])
Node JS FS Module