|
jsio
jsio module
If something seems wrong or incomplete, please enter a comment at the bottom of this page. jsio moduleThis module is based on Netscape Portable Runtime (NSPR) that provides a platform-neutral API for system level and libc like functions. NSPR API is used in the Mozilla client, many of Netscape/AOL/iPlanet's and other software offerings. jsio static membersStatic functionsPollinteger Poll( descriptorArray [, timeout = undefined ] )This function listen for a readable, writable or exception event on each descriptor in descriptorArray. When an event occurs, the function tries to call the corresponding property (function) on the descriptor. IsReadableboolean IsReadable( descriptor )Returns true if the descriptor can be read without blocking. IsWritableboolean IsWritable( descriptor )Returns true if the descriptor can be write without blocking. IntervalNowinteger IntervalNow()Returns the milliseconds value of NSPR's free-running interval timer. UIntervalNowinteger UIntervalNow()Returns the microseconds value of NSPR's free-running interval timer. Sleepvoid Sleep( milliseconds )Sleeps milliseconds milliseconds. GetEnvstring GetEnv( name )Retrieve the value of the given environment variable. GetRandomNoisestring GetRandomNoise( size )Provides, depending on platform, a random value. The length of the random value is dependent on platform and the platform's ability to provide a random value at that moment. WaitSemaphorevoid WaitSemaphore( semaphoreName )Tests the value of the semaphore. If the value of the semaphore is > 0, the value of the semaphore is decremented and the function returns. If the value of the semaphore is 0, the function blocks until the value becomes > 0, then the semaphore is decremented and the function returns. PostSemaphorevoid PostSemaphore( semaphoreName )Increments the value of a specified semaphore. AvailableSpacereal AvailableSpace( path )Returns the available storage space (in bytes) at the given path. Static propertieshostNamestring hostName physicalMemorySizeinteger physicalMemorySize systemInfoObject systemInfo processPriorityinteger processPriorityIs the current process priority among the following values: numberOfProcessorsstring numberOfProcessorsIs the number of processors (CPUs available in an SMP system). currentDirectorystring currentDirectoryGets or sets the current working directory. directorySeparatorstring directorySeparator pathSeparatorstring pathSeparator versionversion class jsio::DescriptorMethodsClosevoid Close()Close the descriptor. Readvalue Read( [amount] )Read amount bytes of data from the current descriptor. If amount is ommited, the whole available data is read. If the descriptor is exhausted (eof or disconnected), this function returns undefined. If the descriptor is a blocking socket and amount is set to the value undefined value, the call blocks until data is available. Writestring Write( data )If the whole data cannot be written, Write returns that have not be written. Syncvoid Sync()Sync any buffered data for a fd to its backing device. Propertiesavailableavailable
typetype closedclosed Static functionsImportImport( nativeDescriptor, type ) ConstantsDESC_FILE DESC_SOCKET_TCP DESC_SOCKET_UDP DESC_LAYERED DESC_PIPE Native Interface
Read the file as a stream. class jsio::DirectoryThis class manages directory I/O Functions. constructorconstructor( directoryName )Creates a new Directory object. MethodsOpenthis Open()Open the directory. Closevoid Close()Close the specified directory. Readstring Read( [, flags = Directory.SKIP_NONE ] )Reads an item of the current directory and go to the next. Makevoid Make()Create the directory given in the constructor. Removeboolean Remove()Removes the directory given in the constructor. Propertiesexistexist namename Static functionsListArray List( dirName [, flags = Directory.SKIP_DOT] )Read all entries of a directory at once. ConstantsSKIP_NONEDo not skip any files.SKIP_DOTSkip the directory entry "." representing the current directory.SKIP_DOT_DOTSkip the directory entry ".." representing the parent directory.SKIP_BOTHSkip both "." and ".." ( same as Directory.SKIP_DOT | Directory.SKIP_DOT_DOT )SKIP_HIDDENSkip hidden files. On Windows platforms and the Mac OS, this value identifies files with the "hidden" attribute set. On Unix platform, this value identifies files whose names begin with a period ("."). Examplevar dir = new Directory( 'c:/tmp' );
dir.Open();
for ( var entry; ( entry = dir.Read() ); ) {
var file = new File(dir.name+'/'+entry);
Print( entry + ' ('+ file.info.type +')', '\n');
}Examplefunction RecursiveDir(path) {
var testList = [];
(function(path) {
var dir = new Directory(path);
dir.Open();
for ( var entry; ( entry = dir.Read(Directory.SKIP_BOTH) ); ) {
var file = new File(dir.name+'/'+entry);
switch ( file.info.type ) {
case File.FILE_DIRECTORY:
arguments.callee(file.name);
break;
case File.FILE_FILE:
testList.push(file.name);
break;
}
}
dir.Close();
})(path);
return testList;
}
Print( RecursiveDir('jshost').join('\n') );class jsio::Filejsio::Descriptorconstructorconstructor( fileName ) MethodsOpenthis Open( flags [, mode] )Open a file for reading, writing, or both. Seekinteger Seek( [ offset = 0 [, whence = File.SEEK_SET ] ] )Moves read-write file offset. Deleteinteger Delete()Delete a file from the filesystem. The operation may fail if the file is open. Lockvoid Lock( state )Lock or unlock a file for exclusive access. state can be true or false. Movevoid Move( directory )Move the file to another directory. Propertiespositioninteger positionGet or set the current position of the file pointer. Same as Seek() function used with SEEK_SET. contentstring contentGet or set the content of the file. If the file does not exist, content is undefined. Setting content with undefined deletes the file. namestring nameContains the name of the file. Changing this value will rename or move the file. existboolean exist infoObject info Static propertiesstandardFile stdin File stdout File stderr Constants???Open modeRDONLY WRONLY RDWR CREATE_FILE APPEND TRUNCATE SYNC EXCL Seek modeSEEK_SET SEEK_CUR SEEK_END info.typeFILE_FILE FILE_DIRECTORY FILE_OTHER Native Interface
Read the file as a stream. Example 1function Copy(fromFilename, toFilename) {
var fromFile = new File(fromFilename).Open(File.RDONLY);
var toFile = new File(toFilename).Open(File.WRONLY | File.CREATE_FILE | File.TRUNCATE);
for ( var buf; buf = fromFile.Read(65536); )
toFile.Write(buf);
toFile.Close();
fromFile.Close();
}Example 2LoadModule('jsstd');
LoadModule('jsio');
try {
var file = new File('file_test.txt');
if ( file.exist ) {
file.Open( File.RDONLY );
Print( 'file content:\n' + file.Read() );
file.Close();
}
} catch ( ex if ex instanceof IoError ) {
Print( 'IOError: ' + ex.text, '\n' );
} catch( ex ) {
throw ex;
}class jsio::MemoryMappedconstructorconstructor( file )Creates a new memory-mapped object using the given opened file descriptor. Propertiesfilefile Native Interface
This object can be used as a buffer source. Examplevar f = new File('directory.cpp');
f.Open("r");
var m = new MemoryMapped(f);
Print(m);class jsio::PipeYou cannot construct this class. class jsio::Processconstructorvalue constructor( path [ , argv ] )This function starts a new process optionaly using the JavaScript Array argv for arguments or undefined for no arguments. MethodsWaitinteger Wait()The function waits the end of the nondetached process and returns its exit code. This function will fail if the process has beed detached. Detachinteger Detach()This function detaches the process. A detached process does not need to be and cannot be reaped. Killinteger Kill()Terminates the process. PropertiesstdinPipe stdin()Is the stdin pipe to the running process. stdoutPipe stdout()Is the stdout pipe to the running process. stderrPipe stderr()Is the stderr pipe to the running process. class jsio::SemaphoreThis class manages interprocess communication semaphores using a counting semaphore model similar to that which is provided in Unix and Windows platforms. constructorconstructor( name, [ count = 0 ] [, mode = Semaphore.IRUSR | Semaphore.IWUSR ] )Create or open a named semaphore with the specified name. If the named semaphore doesn't exist, the named semaphore is created. MethodsWaitvoid Wait()If the value of the semaphore is > 0, decrement the value and return. If the value is 0, sleep until the value becomes > 0, then decrement the value and return. The "test and decrement" operation is performed atomically. Postvoid Post()Increment the value of the named semaphore by 1. ConstantsIRWXUread, write, execute/search by ownerIRUSRread permission, ownerIWUSRwrite permission, ownerIXUSRexecute/search permission, ownerIRWXGread, write, execute/search by groupIRGRPread permission, groupIWGRPwrite permission, groupIXGRPexecute/search permission, groupIRWXOread, write, execute/search by othersIROTHread permission, othersIWOTHwrite permission, othersIXOTHexecute/search permission, others class jsio::SharedMemoryThis class manages shared memory between two or more process. constructorconstructor( name, size [, mode] )Creates a named shared memory area of size bytes using mode linux-like rights. MethodsWriteWrite( data [, offset] )Write data at offset in the shared memory. Readstring Read( length [, offset] )Read length bytes from offset in the shared memory. ClearClear()Clears the content of the shared memory. CloseClose()Close the shared memory. Propertiescontentstring contentRead or write the whole content of the shared memory. Setting undefined as value clears the memory area. Native Interface
This object provide a BufferGet native interface an can be used in any function that support this interface. For example a Stream object. ExempleLoadModule('jsstd');
LoadModule('jsio');
var mem1 = new SharedMemory( 'mytest', 100 );
mem1.Write('foo');
var mem2 = new SharedMemory( 'mytest', 100 );
Print( mem2.Read(3), '\n' );class jsio::Socketjsio::DescriptorSocket class is used to create a non-blocking TCP socket. constructorconstructor( [type = Socket.TCP] )Type can be Socket.TCP or Socket.UDP. MethodsShutdownShutdown( [ what ] )Shut down part of a full-duplex connection on a socket. BindBind( [port] [, ip] )When a new socket is created, it has no address bound to it. Bind assigns the specified address (also known as name) to the socket. ip is the address (interface) to which the socket will be bound. If address is ommited, any address is will match. If port is undefined, the socket is not bind to any port. ListenListen( [ backlogSize = 8 ] )Listen for connections on a socket. backlogSize specifies the maximum length of the queue of pending connections. AcceptSocket Accept()Accept a connection on a socket. This function returns a connected jsio::Socket. Connectthis Connect( host, port [, timeout] )Initiate a connection on a socket. SendTostring SendTo( host, port, string )Send a specified number of bytes from an unconnected socket. See. Static functions. RecvFromstring RecvFrom()Receive all data from socket which may or may not be connected. See. Static functions. TransmitFileTransmitFile( fileDescriptor [, close [, headers [, timeout]]] )Sends a complete file pointed by fileDescriptor across a socket. PropertiesconnectContinueconnectContinue connectionClosedconnectionClosed lingerinteger lingerThe time in milliseconds to linger on close if data present. A value of zero means no linger. noDelayboolean noDelayDon't delay send to coalesce packets. reuseAddrboolean reuseAddrAllow local address reuse. keepAliveboolean keepAliveKeep connections alive. recvBufferSizeinteger recvBufferSizeReceive buffer size. sendBufferSizeinteger sendBufferSizeSend buffer size. maxSegmentinteger maxSegmentMaximum segment size. nonblockingboolean nonblockingNon-blocking (network) I/O. broadcastboolean broadcastEnable broadcast. multicastLoopbackboolean multicastLoopbackIP multicast loopback. peerNamestring peerName peerPortinteger peerPort sockNamestring sockName sockPortinteger sockPort Static functionsGetHostsByNameArray GetHostsByName( hostName )Lookup a host by name and returns the results in a javascript array. SendToSendTosee Socket::SendTo RecvFromRecvFromsee Socket::RecvFrom ConstantsTCP UDP Native Interface
Intresting lectureclass jsio::IoError- top - You cannot construct this class. Properties |
Sign in to add a comment
Perhaps systemInfo.name could use some documentation on what values it returns.
For me I get systemInfo.name, but unless I know what systemInfo.name returns on Windows, I don't know what test to stick in my path handling library.
The underlying API I use (PR_GetSystemInfo?) is not documented enough, then I cannot give a complete list of return values.
"Directory.chdir( File.dirname( "/some/path/to/some/file" ) )" capability would be useful. :)
Directory class: -Static functions: boolean Chdir( string pathname ) --change the current working directory
File class: -Properties: string dirName --returns the absolute path of where the file is located (not the filename)
@deft.productions Most of those kind of path operations are going to be handled by MonkeyScript? JavaScript? side so I don't see to much need to do this kind of stuff in jslibs.