[View]  [Edit]  [Lock]  [References]  [Attachments]  [History]  [Home]  [Changes]  [Search]  [Help] 

test[nodeJS] 044 File Read (async)

"044-4 Reading files with #read:buffer:offset:length:position:with: and #fstat:with:"
| fs content |
fs := NodeJS fs.
fs open: (TestPath, 'Sample.txt') flags:#r with: [:error :fd| 
   error isNil ifFalse: [ ^self error: '044-4 ' ,error ].
   fs fstat: fd with: [:err :stats| | jsObject size |
	  size := (NodeStats @ stats) size.		  
	  jsObject := {'new Buffer(size);'}.		  
	  fs read: fd 
             buffer: jsObject 
             offset: 0 
             length: (jsObject#length) 
             position:0 
             with:[:er :bytesRead :buf|
	        er isNil ifFalse: [ ^self error: '044-4 ',er ].
	        content := (NodeBuffer @ buf) toString:#utf8. 
	        fs closeSync:fd
          ]  		 
   ]   
].
"self print: 'OK-> 044-4 Reading ', content size, ' characters'."


"044-5 Reading files with #readFile:options:with:"
NodeJS fs readFile: (TestPath, 'Sample.txt') options: #utf8 with: [:error :data| 
   error isNil ifFalse: [ ^self error: '044-5 ' ,error ].
   "self print: 'OK-> 044-5 Reading ', data size,' characters'."
].


"044-6 Version 2: Reading files with #readFile:options:with:"
| options |
options := ((#encoding -> #utf8),(#flag -> #r)).
NodeJS fs readFile: (TestPath, 'Sample.txt') options: options with: [:error :data| 
   error isNil ifFalse: [ ^self error: '044-6 ' ,error ].
   "self print: 'OK-> 044-6 Reading ', data size,' characters'."
].


"044-7 Reading files with #readFile:with:"
| content |
NodeJS fs readFile: (TestPath, 'Sample.txt') with: [:error :data| 
   error isNil ifFalse: [ ^self error: '044-7 ' ,error ].
   content := NodeBuffer @ data.
   "self print: 'OK-> 044-7 Reading ', (content toString: #utf8) size, ' characters'."   
].