1+ /***
2+ * The goal of this file is to know about the file system functions;
3+ *
4+ *
5+ * How to run this example:
6+ * 1. node fileSys-1.js
7+ * 2. See the message get displayed on prompt.
8+ */
9+
10+ var fs = require ( 'fs' ) ,
11+ path = require ( 'path' ) ,
12+ filename1 = path . normalize ( 'FixContent/email1.txt' ) ,
13+ filename2 = 'message.txt' ,
14+ filename3 = path . normalize ( 'FixContent/file-a.txt' ) ,
15+ filename4 = path . normalize ( 'FixContent/file-b.txt' ) ;
16+
17+ /***
18+ * Read a file.
19+ */
20+ fs . readFile ( filename1 , 'utf-8' , function ( error , data ) {
21+ if ( error ) throw error ;
22+ console . log ( 'Following are the file content:' ) ;
23+ console . log ( data ) ;
24+ } ) ;
25+
26+ /***
27+ * Write content to a file. If file already exists, Node will remove it and write it.
28+ */
29+ fs . writeFile ( filename2 , 'Hello World' , function ( error ) {
30+ if ( error ) throw error ;
31+ console . log ( 'File is written successfully.' ) ;
32+ } ) ;
33+
34+ /***
35+ * Append content to a file. If file already exists, Node will open it and append the content.
36+ */
37+ fs . appendFile ( filename2 , '\nWelcome to Node.js training sessions.' , function ( error ) {
38+ if ( error ) throw error ;
39+ console . log ( 'Content appended successfully.' ) ;
40+ } ) ;
41+
42+ /***
43+ * Remove a file.
44+ */
45+ fs . unlink ( filename2 , function ( error ) {
46+ if ( error ) throw error ;
47+ console . log ( '%s removed successfully.' , filename2 ) ;
48+ } ) ;
49+
50+ /***
51+ * Rename a file.
52+ */
53+ fs . rename ( filename3 , filename4 , function ( error ) {
54+ if ( error ) throw error ;
55+ console . log ( '%s renamed successfully.' ) ;
56+ } ) ;
0 commit comments