A simple node. JS File System (fs) read/write example.
In nodejs, you can use the fs (file system) module to perform file I/O operations. API link address: the use of fs File System under the http://nodeapi.ucdok.com/#/api/fs.html instance: 1, the module call declaration: var fs = require ('fs'); var path = require ('path '); fs is the file module, and path is the system path module. 2. You can use the writeFile method to write data to a folder. Fs. writeFile (filename, data, [options], callback) filename is the address of the specific file storage path, and data is the data object of the specific file to be written, [options] For saving specific file configuration, encoding format, etc. callback is a specific callback function for corresponding error capture and prompt. The Code is as follows: fs. writeFile (path. join (_ dirname, 'account. js'), JSON. stringify (tempAccount), function (err) {if (err) throw err; console. log ("Export Account Success! ") ;}); Write data to the file path in JSON format. 3. Read the file data using the readFile method. Fs. readFile (filename, [options], callback) filename is the file path and name, and [options] is the specific option configuration, including the data encoding method. callback is the callback function, handle the error and prompt accordingly. The Code is as follows: fs. readFile (path. join (_ dirname, 'account. js'), function (err, bytesRead) {if (err) throw err; console. log (bytesRead) ;}); reads the binary stream file of the data. If you need to encode the specific data, the Code is as follows: copy the code fs. readFile (path. join (_ dirname, 'account. js '), {encoding: 'utf-8'}, function (err, bytesRead) {if (err) throw err; var data = JSON. parse (bytesRead); console. log (data [0]); console. log ("readFile success") ;}); 4. Read the ingwenj name in the folder. Readdir (path, callback) path is the path address of the folder to be read, and callback is the callback function. ReaddirSync (path) is the real-time synchronization version Method for reading files. Path is the specific folder path address. Var data = fs. readdirSync (_ dirname); console. log (data); in this way, simple file writing and reading instances are implemented, and further learning is required for specific in-depth applications. If any error occurs, please forgive me.