My favorites | Sign in
Logo
                
Search
for
Updated May 31, 2009 by soubok
Labels: doc
jsio  
jsio module

If something seems wrong or incomplete, please enter a comment at the bottom of this page.



- source - main - QA -

jsio module

This 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 members

- top - revision -

Static functions

Poll

integer 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.

The function returns the number of events that occurs or 0 if the function timed out.
note:
The property is NOT cleared by the function. If you want to stop receiving an event, you have to remove the property by yourself. eg. delete socket1.writable.


The second argument, timeout, defines the number of milliseconds the function has to wait before returning if no event has occured. timeout can be undefined OR omited, in this case, no timeout is used.
beware:
No timeout means that the function will wait endless for events.
example:
  socket1.readable = function(soc) { Print( soc.Recv(); ) }
  var count = Poll( [socket1, socket2], 1000 );
  if ( count == 0 )
    Print( 'Nothing has been recived' );

IsReadable

boolean IsReadable( descriptor )
Returns true if the descriptor can be read without blocking.

IsWritable

boolean IsWritable( descriptor )
Returns true if the descriptor can be write without blocking.

IntervalNow

integer IntervalNow()
Returns the milliseconds value of NSPR's free-running interval timer.

UIntervalNow

integer UIntervalNow()
Returns the microseconds value of NSPR's free-running interval timer.

Sleep

void Sleep( milliseconds )
Sleeps milliseconds milliseconds.

GetEnv

string GetEnv( name )
Retrieve the value of the given environment variable.

GetRandomNoise

string 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.
beware:
Calls to GetRandomNoise() may use a lot of CPU on some platforms. Some platforms may block for up to a few seconds while they accumulate some noise. Busy machines generate lots of noise, but care is advised when using GetRandomNoise() frequently in your application.

NSPR API

WaitSemaphore

void 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.
note:
The "test and decrement" operation is performed atomically.

PostSemaphore

void PostSemaphore( semaphoreName )
Increments the value of a specified semaphore.

AvailableSpace

real AvailableSpace( path )
Returns the available storage space (in bytes) at the given path.
example:
  Print( AvailableSpace('/var') );

Static properties

hostName

string hostName
Is the host name with the domain name (if any).

physicalMemorySize

integer physicalMemorySize
Is the amount of physical RAM in the system in bytes.

systemInfo

Object systemInfo
Returns an object that contains the following properties:
  • string architecture: x86, ...
  • string name: Linux, Windows_NT, ...
  • string release: 2.6.22.18, 5.1, ...
example:
  LoadModule('jsstd');
  LoadModule('jsio');
  Print( systemInfo.toSource() );
prints:
  • on coLinux: ({architecture:"x86", name:"Linux", release:"2.6.22.18-co-0.7.3"})
  • on WinXP: ({architecture:"x86", name:"Windows_NT", release:"5.1"})

processPriority

integer processPriority
Is the current process priority among the following values:
  • -1: low
  • 0: normal
  • 1: high
  • 2: urgent

numberOfProcessors

string numberOfProcessors
Is the number of processors (CPUs available in an SMP system).

currentDirectory

string currentDirectory
Gets or sets the current working directory.
example:
  currentDirectory = '/home/foobar';

directorySeparator

string directorySeparator
Get the host' directory separator.
example:
  var isRootDir = (currentDirectory == directorySeparator);

pathSeparator

string pathSeparator
Get the host' path separator.
example:
  Print( GetEnv('PATH').split(<b>pathSeparator</b>) )

version

version
Hold the current version of NSPR.

class jsio::Descriptor

- top - revision -

Methods

Close

void Close()
Close the descriptor.

Read

value 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.
beware:
This function returns a Blob or a string literal as empty string.
example:
  LoadModule('jsstd');
  LoadModule('jsio');

  var soc = new Socket();
  soc.Connect('www.google.com', 80);
  soc.Write('GET\r\n\r\n');
  Print( soc.Read(undefined), '\n' );

Write

string Write( data )
If the whole data cannot be written, Write returns that have not be written.

Sync

void Sync()
Sync any buffered data for a fd to its backing device.

Properties

available

available
Determine the amount of data in bytes available for reading on the descriptor.

type

type
see constants below.

closed

closed
Is true if the file descriptor is closed.
beware:
Do not confuse with disconnected.

eg. A socket descriptor can be open but disconnected.

Static functions

Import

Import( nativeDescriptor, type )

Constants

DESC_FILE
DESC_SOCKET_TCP
DESC_SOCKET_UDP
DESC_LAYERED
DESC_PIPE

Native Interface


class jsio::Directory

- top - revision -

This class manages directory I/O Functions.

constructor

constructor( directoryName )
Creates a new Directory object.
arguments:
  1. string directoryName

Methods

Open

this Open()
Open the directory.

Close

void Close()
Close the specified directory.

Read

string Read( [, flags = Directory.SKIP_NONE ] )
Reads an item of the current directory and go to the next.
arguments:
  1. enum flags: specifies how special files are processed.
return value:
A single directory item.

Make

void Make()
Create the directory given in the constructor.

Remove

boolean Remove()
Removes the directory given in the constructor.
return value:
returns false If the directory is not empty else it returns true.

Properties

exist

exist
Check if the directory exists.

name

name
Returns the name of the directory.

Static functions

List

Array List( dirName [, flags = Directory.SKIP_DOT] )
Read all entries of a directory at once.
arguments:
  1. string dirName: is the path of the directory.
  2. enum flags: specifies how special files are processed.
return value:
All entries in the directory name.
note:
This function supports additional flags: Directory.SKIP_FILE, Directory.SKIP_DIRECTORY, Directory.SKIP_OTHER
example:
  LoadModule('jsstd');
  LoadModule('jsio');
  Print( Directory.List('.').join('\n'), '\n' );

Constants

SKIP_NONE
Do not skip any files.
SKIP_DOT
Skip the directory entry "." representing the current directory.
SKIP_DOT_DOT
Skip the directory entry ".." representing the parent directory.
SKIP_BOTH
Skip both "." and ".." ( same as Directory.SKIP_DOT | Directory.SKIP_DOT_DOT )
SKIP_HIDDEN
Skip 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 (".").

Example

var 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');
}

Example

function 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::Descriptor

- top - revision -

constructor

constructor( fileName )

Methods

Open

this Open( flags [, mode] )
Open a file for reading, writing, or both.

flags is either a combinaison of open mode constants or a string that contains fopen like flags (+, r, w, a).

The functions returns the file object itself (this), this allows to write things like: new File('foo.txt').Open('r').Read();

Seek

integer Seek( [ offset = 0 [, whence = File.SEEK_SET ] ] )
Moves read-write file offset.

Delete

integer Delete()
Delete a file from the filesystem. The operation may fail if the file is open.

Lock

void Lock( state )
Lock or unlock a file for exclusive access. state can be true or false.

Move

void Move( directory )
Move the file to another directory.

Properties

position

integer position
Get or set the current position of the file pointer. Same as Seek() function used with SEEK_SET.

content

string content
Get or set the content of the file. If the file does not exist, content is undefined. Setting content with undefined deletes the file.

name

string name
Contains the name of the file. Changing this value will rename or move the file.

exist

boolean exist
Contains true if the file exists.

info

Object info
This property works with opened and closed files. Contains an object that has the following properties:
  • type : Type of file.
  • size : Size, in bytes, of file's contents.
  • creationTime : Creation time (elapsed milliseconds since 1970.1.1).
  • modifyTime : Last modification time (elapsed milliseconds since 1970.1.1).
note:
Time is relative to midnight (00:00:00), January 1, 1970 Greenwich Mean Time (GMT).
beware:
File time resolution depends of hte underlying filesystem.

eg. the resolution of create time on FAT is 10 milliseconds, while write time has a resolution of 2 seconds and access time has a resolution of 1 day.
example:
   var f = new File('test.txt');
   f.content = '123';
   Print( new Date( f.info.modifyTime ) );

Static properties

standard

File stdin
Is a jsio::File that represents the standard input.
File stdout
Is a jsio::File that represents the standard output.
File stderr
Is a jsio::File that represents the standard error.

Constants

???

Open mode
RDONLY
WRONLY
RDWR
CREATE_FILE
APPEND
TRUNCATE
SYNC
EXCL
Seek mode
SEEK_SET
SEEK_CUR
SEEK_END
info.type
FILE_FILE
FILE_DIRECTORY
FILE_OTHER

Native Interface

Example 1

function 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 2

LoadModule('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::MemoryMapped

- top - revision -

constructor

constructor( file )
Creates a new memory-mapped object using the given opened file descriptor.
arguments:
  1. File file: any opened file descriptor.

Properties

file

file
is the file descriptor used to construct this object.

Native Interface

Example

var f = new File('directory.cpp');
f.Open("r");
var m = new MemoryMapped(f);
Print(m);

class jsio::Pipe

- top - revision -

You cannot construct this class.

The aim of this class is to provide a way to access Descriptor properties and methods from an existing pipe.

exemple:
 var p = new Process( 'c:\\windows\\System32\\cmd.exe', ['/c', 'dir', 'c:'] );
 p.Wait();
 Print( p.stdout.Read() );

class jsio::Process

- top - revision -

constructor

value constructor( path [ , argv ] )
This function starts a new process optionaly using the JavaScript Array argv for arguments or undefined for no arguments.
note:
The new process inherits the environment of the parent process.
exemple:
  var p = new Process( 'c:\\windows\\System32\\cmd.exe', ['/c', 'dir', 'c:'] );
  p.Wait();
  Print( p.stdout.Read() );

Methods

Wait

integer 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.
note:
In bash, true;echo $? prints 0 and false;echo $? prints 1

Detach

integer Detach()
This function detaches the process. A detached process does not need to be and cannot be reaped.

Kill

integer Kill()
Terminates the process.

Properties

stdin

Pipe stdin()
Is the stdin pipe to the running process.

stdout

Pipe stdout()
Is the stdout pipe to the running process.

stderr

Pipe stderr()
Is the stderr pipe to the running process.

class jsio::Semaphore

- top - revision -

This class manages interprocess communication semaphores using a counting semaphore model similar to that which is provided in Unix and Windows platforms.

constructor

constructor( 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.
exemple:
  <b><font color="red">TBD</font></b>

Methods

Wait

void 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.

Post

void Post()
Increment the value of the named semaphore by 1.

Constants

IRWXU
read, write, execute/search by owner
IRUSR
read permission, owner
IWUSR
write permission, owner
IXUSR
execute/search permission, owner
IRWXG
read, write, execute/search by group
IRGRP
read permission, group
IWGRP
write permission, group
IXGRP
execute/search permission, group
IRWXO
read, write, execute/search by others
IROTH
read permission, others
IWOTH
write permission, others
IXOTH
execute/search permission, others

class jsio::SharedMemory

- top - revision -

This class manages shared memory between two or more process.

constructor

constructor( name, size [, mode] )
Creates a named shared memory area of size bytes using mode linux-like rights.

Methods

Write

Write( data [, offset] )
Write data at offset in the shared memory.

Read

string Read( length [, offset] )
Read length bytes from offset in the shared memory.

Clear

Clear()
Clears the content of the shared memory.

Close

Close()
Close the shared memory.

Properties

content

string content
Read or write the whole content of the shared memory. Setting undefined as value clears the memory area.

Native Interface

Exemple

LoadModule('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::Descriptor

- top - revision -

Socket class is used to create a non-blocking TCP socket.

constructor

constructor( [type = Socket.TCP] )
Type can be Socket.TCP or Socket.UDP.

Methods

Shutdown

Shutdown( [ what ] )
Shut down part of a full-duplex connection on a socket.

if what is ALSE, further receives will be disallowed.

if what is true, further sends will be disallowed.

if what is ommited or undefined, further sends and receives will be disallowed

Bind

Bind( [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.
return value:
ALSE if the address is already is in use otherwise true.
example 1:
  var server = new Socket();
  server.Bind(8099, '127.0.0.1');
  server.Listen();
example 2:
  var client = new Socket();
  client.Bind(0, '192.168.0.1');
  client.Connect('127.0.0.1', 8099);

Listen

Listen( [ backlogSize = 8 ] )
Listen for connections on a socket. backlogSize specifies the maximum length of the queue of pending connections.

Accept

Socket Accept()
Accept a connection on a socket. This function returns a connected jsio::Socket.

Connect

this Connect( host, port [, timeout] )
Initiate a connection on a socket.

SendTo

string SendTo( host, port, string )
Send a specified number of bytes from an unconnected socket. See. Static functions.

RecvFrom

string RecvFrom()
Receive all data from socket which may or may not be connected. See. Static functions.

TransmitFile

TransmitFile( fileDescriptor [, close [, headers [, timeout]]] )
Sends a complete file pointed by fileDescriptor across a socket.

headers is a string that contains the headers to send across the socket prior to sending the file.

Optionally, close flag specifies that transmitfile should close the socket after sending the data.

timeout is the time limit for completion of the transmit operation.
note:
This function only works with blocking sockets.

Properties

connectContinue

connectContinue
Test if a nonblocking connect has completed. Is true if the socket is connected.

Is undefined if the operation is still in progress.

Is ALSE if the connection is refused.

connectionClosed

connectionClosed
Check if the socket connection is closed.

linger

integer linger
The time in milliseconds to linger on close if data present. A value of zero means no linger.

noDelay

boolean noDelay
Don't delay send to coalesce packets.

reuseAddr

boolean reuseAddr
Allow local address reuse.

keepAlive

boolean keepAlive
Keep connections alive.

recvBufferSize

integer recvBufferSize
Receive buffer size.

sendBufferSize

integer sendBufferSize
Send buffer size.

maxSegment

integer maxSegment
Maximum segment size.

nonblocking

boolean nonblocking
Non-blocking (network) I/O.

broadcast

boolean broadcast
Enable broadcast.

multicastLoopback

boolean multicastLoopback
IP multicast loopback.

peerName

string peerName
Get name of the connected peer. Return the network address for the connected peer socket.

peerPort

integer peerPort
Get port of the connected peer. Return the port for the connected peer socket.

sockName

string sockName
Get socket name. Return the network address for this socket.

sockPort

integer sockPort
Get socket port. Return the port for this socket.

Static functions

GetHostsByName

Array GetHostsByName( hostName )
Lookup a host by name and returns the results in a javascript array.

SendTo

SendTo
see Socket::SendTo

RecvFrom

RecvFrom
see Socket::RecvFrom

Constants

TCP
UDP

Native Interface

Intresting lecture

  1. Five pitfalls of Linux sockets programming

class jsio::IoError

- top -

You cannot construct this class.

Its aim is to throw as an exception on any NSPR runtime error.

Properties


- top - main -


Comment by nadir.seen.fire, Nov 29, 2008

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.

Comment by soubok, Nov 30, 2008

The underlying API I use (PR_GetSystemInfo?) is not documented enough, then I cannot give a complete list of return values.

Comment by deft.productions, Dec 18, 2008

"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)

Comment by nadir.seen.fire, Feb 23, 2009

@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.


Sign in to add a comment
Hosted by Google Code