Node.js File System (FS)In Node.js, file I/O is provided by simple wrappers around standard POSIX functions. Node File System (fs) module can be imported using following syntax: Syntax: Node.js FS Reading FileEvery method in fs module has synchronous and asynchronous forms. Asynchronous methods take a last parameter as completion function callback. Asynchronous method is preferred over synchronous method because it never blocks the program execution where as the synchronous method blocks. Let's take an example: Create a text file named "input.txt" having the following content. File: input.txt Let's take an example to create a JavaScript file named "main.js" having the following code: File: main.js Open Node.js command prompt and run the main.js: Node.js Open a fileSyntax: Following is the syntax of the method to open a file in asynchronous mode: Parameter explanation: Following is the description of parameters used in the above syntax: path: This is a string having file name including path. flags: Flag specifies the behavior of the file to be opened. All possible values have been mentioned below. mode: This sets the file mode (permission and sticky bits), but only if the file was created. It defaults to 0666, readable and writeable. callback: This is the callback function which gets two arguments (err, fd). Node.js Flags for Read/WriteFollowing is a list of flags for read/write operation:
Create a JavaScript file named "main.js" having the following code to open a file input.txt for reading and writing. File: main.js Open Node.js command prompt and run the main.js: Node.js File Information MethodSyntax: Following is syntax of the method to get file information. Parameter explanation: Path: This is string having file name including path. Callback: This is the callback function which gets two arguments (err, stats) where stats is an object of fs.Stats type. Node.js fs.Stats class Methods
Let's take an example to create a JavaScript file named main.js having the following code: File: main.js Now open the Node.js command prompt and run the main.js Next TopicNode.js Path |