File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed
Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ const fs = require ( 'fs' ) ;
2+
3+ fs . writeFile ( 'test.txt' , 'Hello world' , ( error ) => {
4+ if ( error ) {
5+ console . error ( error ) ;
6+ return ;
7+ }
8+ console . log ( 'Write complete' ) ;
9+ } ) ;
10+
11+ // After running above code:
12+ fs . readFile ( 'test.txt' , 'utf-8' , ( error , data ) => {
13+ if ( error ) {
14+ console . error ( error ) ;
15+ }
16+ console . log ( data ) ;
17+ } ) ;
18+
19+ // Read from no file
20+ fs . readFile ( 'nofile.txt' , 'utf-8' , ( error , data ) => {
21+ if ( error ) {
22+ console . error ( error ) ;
23+ }
24+ console . log ( data ) ;
25+ } ) ;
26+
27+ // Readfile promisified
28+ function readFile ( file , options ) {
29+ return new Promise ( ( resolve , reject ) => {
30+ fs . readFile ( file , options , ( error , data ) => {
31+ if ( error ) {
32+ return reject ( error ) ;
33+ }
34+ resolve ( data ) ;
35+ } )
36+ } )
37+ }
38+
39+ // New usage after Node 10
40+ const fsPromises = require ( 'fs' ) . promises ;
41+ fsPromises . readFile ( 'test.txt' , 'utf-8' ) . then ( console . log ) ;
42+
43+ fsPromises . stat ( 'test.txt' ) . then ( console . log ) ;
You can’t perform that action at this time.
0 commit comments