YouTip LogoYouTip

Nodejs Fs

The Node.js file system module (fs module) provides a rich API for reading, writing, deleting files, and performing other file system operations. The fs module supports both asynchronous and synchronous methods, allowing developers to choose the appropriate approach for file operations based on specific needs. ### Importing the fs Module First, you need to import the fs module: var fs = require("fs") * * * ## Asynchronous and Synchronous Methods in the Node.js file system (fs module) have both asynchronous and synchronous versions. For example, the functions for reading file contents include the asynchronous `fs.readFile()` and the synchronous `fs.readFileSync()`. The last parameter of an asynchronous method function is a callback function. The first parameter of the callback function contains error information (error). It is recommended to use asynchronous methods. Compared to synchronous methods, asynchronous methods have higher performance, are faster, and do not block execution. ### Example Create a file named `example.txt` with the following content: tutorial website address: www..com File read example Create a file named `file.js` with the following code: ## Example var fs = require("fs"); // Asynchronous read fs.readFile('input.txt',function(err, data){ if(err){ return console.error(err); } console.log("Asynchronous read: "+ data.toString()); }); // Synchronous read var data = fs.readFileSync('example.txt'); console.log("Synchronous read: "+ data.toString()); console.log("Program execution completed."); The execution result of the above code is as follows: $ node file.js Synchronous read: tutorial website address: www..com File read exampleProgram execution completed.Asynchronous read: tutorial website address: www..com File read example ### Writing to a File Asynchronous file writing: fs.writeFile('example.txt', 'Hello, World!', (err) => { if (err) { console.error('Error writing file:', err); return; } console.log('File written successfully');}); Synchronous file writing: try { fs.writeFileSync('example.txt', 'Hello, World!'); console.log('File written successfully');} catch (err) { console.error('Error writing file:', err);} ### Appending Content to a File Asynchronous appending: fs.appendFile('example.txt', 'nAppending some text', (err) => { if (err) { console.error('Error appending to file:', err); return; } console.log('Text appended successfully');}); Synchronous appending: try { fs.appendFileSync('example.txt', 'nAppending some text'); console.log('Text appended successfully');} catch (err) { console.error('Error appending to file:', err);} ### Deleting a File Asynchronous file deletion: fs.unlink('example.txt', (err) => { if (err) { console.error('Error deleting file:', err); return; } console.log('File deleted successfully');}); Synchronous file deletion: try { fs.unlinkSync('example.txt'); console.log('File deleted successfully');} catch (err) { console.error('Error deleting file:', err);} ### Creating a Directory Asynchronous directory creation: fs.mkdir('new_directory', (err) => { if (err) { console.error('Error creating directory:', err); return; } console.log('Directory created successfully');}); Synchronous directory creation: try { fs.mkdirSync('new_directory'); console.log('Directory created successfully');} catch (err) { console.error('Error creating directory:', err);} ### Reading Directory Contents Asynchronous directory reading: fs.readdir('new_directory', (err, files) => { if (err) { console.error('Error reading directory:', err); return; } console.log('Directory contents:', files);}); Synchronous directory reading: try { const files = fs.readdirSync('new_directory'); console.log('Directory contents:', files);} catch (err) { console.error('Error reading directory:', err);} ### Checking if a File or Directory Exists Asynchronous check: fs.access('example.txt', fs.constants.F_OK, (err) => { if (err) { console.log('File does not exist'); } else { console.log('File exists'); }}); Synchronous check: try { fs.accessSync('example.txt', fs.constants.F_OK); console.log('File exists');} catch (err) { console.log('File does not exist');} ### Advanced Usage **1. File Streams** File streams can be used to efficiently read and write large files without loading the entire file into memory at once. Reading a file stream: const fs = require('fs');const readableStream = fs.createReadStream('large_file.txt', 'utf8'); readableStream.on('data', (chunk) => { console.log('Received chunk:', chunk);}); readableStream.on('end', () => { console.log('No more data.');}); Writing a file stream: const fs = require('fs');const writableStream = fs.createWriteStream('output.txt'); writableStream.write('Hello, '); writableStream.write('World!n'); writableStream.end(); writableStream.on('finish', () => { console.log('All writes are now complete.');}); **2. File System Statistics** You can use `fs.stat` or `fs.lstat` to get statistics for a file or directory. Asynchronously getting statistics: fs.stat('example.txt', (err, stats) => { if (err) { console.error('Error getting stats:', err); return; } console.log('Is file?', stats.isFile()); console.log('Is directory?', stats.isDirectory()); console.log('Size:', stats.size);}); Synchronously getting statistics: try { const stats = fs.statSync('example.txt'); console.log('Is file?', stats.isFile()); console.log('Is directory?', stats.isDirectory()); console.log('Size:', stats.size);} catch (err) { console.error('Error getting stats:', err);} Next, let's take a closer look at the methods of the Node.js file system. * * * ## Opening Files ### Syntax The following is the syntax for opening a file in asynchronous mode: fs.open(path, flags[, mode], callback) ### Parameters The parameters are described as follows: * **path** - The path to the file. * **flags** - The behavior for opening the file. Specific values are detailed below. * **mode** - Sets the file mode (permissions). The default permission for file creation is 0666 (readable, writable). * **callback** - The callback function, with two parameters like: callback(err, fd). The `flags` parameter can be one of the following values: | Flag | Description | | --- | --- | | r | Opens the file in read-only mode. The file must exist. If the file does not exist, an exception is thrown. | | r+ | Opens the file in read-write mode. The file must exist. | | rs | Opens the file in synchronous read-only mode. Blocking operation, but may provide better stability on some operating systems. | | rs+ | Opens the file in synchronous read-write mode. Blocking operation, but may provide better stability on some operating systems. | | w | Opens the file in write-only mode. If the file does not exist, it is created. If the file exists, it is truncated. | | wx | Similar to 'w', but fails if the path exists. | | w+ | Opens the file in read-write mode. If the file does not exist, it is created. If the file exists, it is truncated. | | wx+ | Similar to 'w+', but fails if the path exists. | | a | Opens the file in append mode. If the file does not exist, it is created. | | ax | Similar to 'a', but fails if the path exists. | | a+ | Opens the file in read and append mode. If the file does not exist, it is created. | | ax+ | Similar to 'a+', but fails if the path exists. | ### Example Next, we create a `file.js` file and open `input.txt` for reading and writing. The code is as follows: var fs = require("fs");// Asynchronous file opening console.log("Preparing to open file!"); fs.open('input.txt', 'r+', function(err, fd) { if (err) { return console.error(err); } console.log("File opened successfully!"); }); The execution result of the above code is as follows: $ node file.js Preparing to open file!File opened successfully! * * * ## Getting File Information ### Syntax The following is the syntax for getting file information in asynchronous mode: fs.stat(path, callback) ### Parameters The parameters are described as follows: * **path** - The file path. * **callback** - The callback function, with two parameters like: (err, stats), where **stats** is an `fs.Stats` object. After `fs.stat(path)` is executed, an instance of the `stats` class is returned to its callback function. You can use the methods provided in the `stats` class to determine the relevant attributes of the file. For example, to determine if it is a file: var fs = require('fs'); fs.stat('/Users/liuht/code/itbilu/demo/fs.js', function (err, stats) { console.log(stats.isFile()); //true}) The methods in the `stats` class are: | Method | Description | | --- | --- | | stats.isFile() | Returns true if it is a file, otherwise returns false. | | stats.isDirectory() | Returns true if it is a directory, otherwise returns false. | | stats.isBlockDevice() | Returns true if it is a block device, otherwise returns false. | | stats.isCharacterDevice() | Returns true if it is a character device, otherwise returns false. | | stats.isSymbolicLink() | Returns true if it is a symbolic link, otherwise returns false. | | stats.isFIFO() | Returns true if it is a FIFO, otherwise returns false. FIFO is a special type of named pipe in UNIX. | | stats.isSocket() | Returns true if it is a Socket, otherwise returns false. | ### Example Next, we create a `file.js` file. The code is as follows: var fs = require("fs"); console.log("Preparing to open file!"); fs.stat('input.txt', function (err, stats) { if (err) { return console.error(err); } console.log(stats); console.log("File information read successfully!"); // Check file type console.log("Is it a file (isFile) ? " + stats.isFile()); console.log("Is it a directory (isDirectory) ? " + stats.isDirectory()); }); The execution result of the above code is as follows: $ node file.js Preparing to open file!{ dev: 16777220, mode: 33188, nlink: 1, uid: 501, gid: 20, rdev: 0, blksize: 4096, ino: 40333161, size: 61, blocks: 8, atime: Mon Sep 07 2015 17:43:55 GMT+0800 (CST), mtime: Mon Sep 07 2015 17:22:35 GMT+0800 (CST), ctime: Mon Sep 07 2015 17:22:35 GMT+0800 (CST) }File information read successfully!Is it a file (isFile) ? trueIs it a directory (isDirectory) ? false * * * ## Writing to a File ### Syntax The following is the syntax for writing to a file in asynchronous mode: fs.writeFile(file, data[, options], callback) `writeFile` opens the file directly in 'w' mode by default. Therefore, if the file exists, the content written by this method will overwrite the old file content. ### Parameters The parameters are described as follows: * **file** - The filename or file descriptor. * **data** - The data to write to the file. It can be a String or Buffer object. * **options** - This parameter is an object containing `{encoding, mode, flag}`. The default encoding is 'utf8', mode is 0666, and flag is 'w'. * **callback** - The callback function. The callback function only contains the error information parameter (err), which is returned when writing fails. ### Example Next, we create a `file.js` file. The code is as follows: var fs = require("fs"); console.log("Preparing to write to file"); fs.writeFile('input.txt', 'This is content written via fs.writeFile', function(err) { if (err) { return console.error(err); } console.log("Data written successfully!"); console.log("--------This is a divider-------------") console.log("Reading the written data!"); fs.readFile('input.txt', function (err, data) { if (err) { return console.error(err); } console.log("Asynchronous read of file data: " + data.toString()); });}); The execution result of the above code is as follows: $ node file.js Preparing to write to fileData written successfully!--------This is a divider-------------Reading the written data!Asynchronous read of file data: This is content written via fs.writeFile * * * ## Reading a File ### Syntax The following is the syntax for reading a file in asynchronous mode: fs.read(fd, buffer, offset, length, position, callback) This method uses a file descriptor to read the file. ### Parameters The parameters are described as follows: * **fd** - The file descriptor returned by the `fs.open()` method. * **buffer** - The buffer that data is written to. * **offset** - The offset in the buffer at which to start writing. * **length** - The number of bytes to read from the file. * **position** - The position in the file to start reading from. If the value of `position` is null, data will be read from the current file pointer position. * **callback** - The callback function, with three parameters: err, bytesRead, buffer. `err` is the error information, `bytesRead` indicates the number of bytes read, and `buffer` is the buffer object. ### Example The content of `input.txt` is: tutorial website address: www..com Next, we create a `file.js` file. The code is as follows: var fs = require("fs");var buf = new Buffer.alloc(1024); console.log("Preparing to open an existing file!"); fs.open('input.txt', 'r+', function(err, fd) { if (err) { return console.error(err); } console.log("File opened successfully!"); console.log("Preparing to read the file:"); fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){ if (err){ console.log(err); } console.log(bytes + " bytes were read"); // Output only the read bytes if(bytes > 0){ console.log(buf.slice(0, bytes).toString()); } });}); The execution result of the above code is as follows: $ node file.js Preparing to open an existing file!File opened successfully!Preparing to read the file:42 bytes were readTutorial tutorial website address: www..com * * * ## Closing a File ### Syntax The following is the syntax for closing a file in asynchronous mode: fs.close(fd, callback) This method uses a file descriptor to read the file. ### Parameters The parameters are described as follows: * **fd** - The file descriptor returned by the `fs.open()` method. * **callback** - The callback function, with no parameters. ### Example The content of `input.txt` is: tutorial website address: www..com Next, we create a `file.js` file. The code is as follows: var fs = require("fs");var buf = new Buffer.alloc(1024); console.log("Preparing to open file!"); fs.open('input.txt', 'r+', function(err, fd) { if (err) { return console.error(err); } console.log("File opened successfully!"); console.log("Preparing to read the file!"); fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){ if (err){ console.log(err); } // Output only the read bytes if(bytes > 0){ console.log(buf.slice(0, bytes).toString()); } // Close the file fs.close(fd, function(err){ if (err){ console.log(err); } console.log("File closed successfully"); }); });}); The execution result of the above code is as follows: $ node file.js Preparing to open file!File opened successfully!Preparing to read the file! tutorial website address: www..com File closed successfully * * * ## Truncating a File ### Syntax The following is the syntax for truncating a file in asynchronous mode: fs.ftruncate(fd, len, callback) This method uses a file descriptor to read the file. ### Parameters The parameters are described as follows: * **fd** - The file descriptor returned by the `fs.open()` method. * **len** - The length to truncate the file content to. * **callback** - The callback function, with no parameters. ### Example The content of `input.txt` is: site:www..com Next, we create a `file.js` file. The code is as follows: var fs = require("fs");var buf = new Buffer.alloc(1024); console.log("Preparing to open file!"); fs.open('input.txt', 'r+', function(err, fd) { if (err) { return console.error(err); } console.log("File opened successfully!"); console.log("Truncating file content to within 10 bytes, excess will be removed."); // Truncate the file fs.ftruncate(fd, 10, function(err){ if (err){ console.log(err); } console.log("File truncated successfully."); console.log("Reading the same file"); fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){ if (err){ console.log(err); } // Output only the read bytes if(bytes > 0){ console.log(buf.slice(0, bytes).toString()); } // Close the file fs.close(fd, function(err){ if (err){ console.log(err); } console.log("File closed successfully!"); }); }); });}); The execution result of the above code is as follows: $ node file.js Preparing to open file!File opened successfully!Truncating file content to within 10 bytes, excess will be removed.File truncated successfully.Reading the same file site:www.r File closed successfully * * * ## Deleting a File ### Syntax The following is the syntax for deleting a file: fs.unlink(path, callback) ### Parameters The parameters are described as follows: * **path** - The file path. * **callback** - The callback function, with no parameters. ### Example The content of `input.txt` is: site:www..com Next, we create a `file.js` file. The code is as follows: var fs = require("fs"); console.log("Preparing to delete file!"); fs.unlink('input.txt', function(err) { if (err) { return console.error(err); } console.log("File deleted successfully!");}); The execution result of the above code is as follows: $ node file.js Preparing to delete file!File deleted successfully! If you check the `input.txt` file again, you will find it no longer exists. * * * ## Creating a Directory ### Syntax The following is the syntax for creating a directory: fs.mkdir(path[, options], callback) ### Parameters The parameters are described as follows: * **path** - The file path. * The `options` parameter can be: * **recursive** - Whether to create directories recursively. The default is false. * **mode** - Sets the directory permissions. The default is 0777. * **callback** - The callback function, with no parameters. ### Example Next, we create a `file.js` file. The code is as follows: var fs = require("fs");// The /tmp directory must exist console.log("Creating directory /tmp/test/"); fs.mkdir("/tmp/test/",function(err){ if (err) { return console.error(err); } console.log("Directory created successfully.");}); The execution result of the above code is as follows: $ node file.js Creating directory /tmp/test/Directory created successfully. You can add the `recursive: true` parameter to create directories regardless of whether `/tmp` and `/tmp/a` exist: fs.mkdir('/tmp/a/apple', { recursive: true }, (err) => { if (err) throw err;}); * * * ## Reading a Directory ### Syntax The following is the syntax for reading a directory: fs.readdir(path, callback) ### Parameters The parameters are described as follows: * **path** - The file path. * **callback** - The callback function. The callback function has two parameters: err, files. `err` is the error information, and `files` is an array list of files in the directory. ### Example Next, we create a `file.js` file. The code is as follows: var fs = require("fs"); console.log("Viewing /tmp directory"); fs.readdir("/tmp/",function(err, files){ if (err) { return console.error(err); } files.forEach( function (file){ console.log( file ); });}); The execution result of the above code is as follows: $ node file.js Viewing /tmp directory input.out output.out te
← Ruby TutorialNodejs Util β†’