code
stringlengths 10
343k
| docstring
stringlengths 36
21.9k
| func_name
stringlengths 1
3.35k
| language
stringclasses 1
value | repo
stringlengths 7
58
| path
stringlengths 4
131
| url
stringlengths 44
195
| license
stringclasses 5
values |
---|---|---|---|---|---|---|---|
const extension = exports.extension = function(path) {
let name = base(path);
if (!name) {
return '';
}
name = name.replace(/^\.+/, '');
const index = name.lastIndexOf('.');
return index > 0 ? name.substring(index) : '';
} | Return the extension of a given path. That is everything after the last dot
in the basename of the given path, including the last dot. Returns an empty
string if no valid extension exists.
@param {String} path
@returns {String} the file's extension
@example >> fs.extension('test.txt');
'.txt' | exports.extension ( path ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const split = exports.split = function(path) {
if (!path) {
return [];
}
return String(path).split(SEPARATOR_RE);
} | Split a given path into an array of path components.
@param {String} path
@returns {Array} the path components
@example >> fs.split('/Users/someuser/Desktop/subdir/test.txt');
[ '', 'Users', 'someuser', 'Desktop', 'subdir', 'test.txt' ] | exports.split ( path ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const normal = exports.normal = function(path) {
return resolve(path);
} | Normalize a path by removing '.' and simplifying '..' components, wherever
possible.
@param {String} path
@returns {String} the normalized path
@example >> fs.normal('../redundant/../foo/./bar.txt');
'../foo/bar.txt' | exports.normal ( path ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const resolve = exports.resolve = function() {
const elements = [];
let root = '';
let leaf = '';
let path;
for (let i = 0; i < arguments.length; i++) {
path = String(arguments[i]);
if (path.trim() === '') {
continue;
}
let parts = path.split(SEPARATOR_RE);
// Checking for absolute paths is not enough here as Windows has
// something like quasi-absolute paths where a path starts with a
// path separator instead of a drive character, e.g. \home\projects.
if (isAbsolute(path) || SEPARATOR_RE.test(path[0])) {
// path is absolute, throw away everyting we have so far.
// We still need to explicitly make absolute for the quasi-absolute
// Windows paths mentioned above.
root = String(getPath(parts.shift() + SEPARATOR).toAbsolutePath());
elements.length = 0;
}
leaf = parts.pop();
if (leaf === '.' || leaf === '..') {
parts.push(leaf);
leaf = '';
}
for (let j = 0; j < parts.length; j++) {
let part = parts[j];
if (part === '..') {
if (elements.length > 0 && arrays.peek(elements) !== '..') {
elements.pop();
} else if (!root) {
elements.push(part);
}
} else if (part !== '' && part !== '.') {
elements.push(part);
}
}
}
path = elements.join(SEPARATOR);
if (path.length > 0) {
leaf = SEPARATOR + leaf;
}
return root + path + leaf;
} | Join a list of paths by starting at an empty location and iteratively
"walking" to each path given. Correctly takes into account both relative and
absolute paths.
@param {String...} paths... the paths to resolve
@return {String} the joined path
@example >> fs.resolve('../.././foo/file.txt', 'bar/baz/', 'test.txt');
'../../foo/bar/baz/test.txt' | exports.resolve ( ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const relative = exports.relative = function(source, target) {
if (!target) {
target = source;
source = workingDirectory();
}
source = absolute(source);
target = absolute(target);
source = source.split(SEPARATOR_RE);
target = target.split(SEPARATOR_RE);
source.pop();
while (source.length && target.length && target[0] === source[0]) {
source.shift();
target.shift();
}
while (source.length) {
source.shift();
target.unshift("..");
}
return target.join(SEPARATOR);
} | Establish the relative path that links source to target by strictly
traversing up ('..') to find a common ancestor of both paths. If the target
is omitted, returns the path to the source from the current working
directory.
@param {String} source
@param {String} target
@returns {String} the path needed to change from source to target
@example >> fs.relative('foo/bar/', 'foo/baz/');
'../baz/'
>> fs.relative('foo/bar/', 'foo/bar/baz/');
'baz/' | exports.relative ( source , target ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const move = exports.move = function(source, target) {
const from = resolvePath(source);
const to = resolvePath(target);
Files.move(from, to, [StandardCopyOption.REPLACE_EXISTING]);
} | Move a file from `source` to `target`. If `target` already exists,
it is replaced by the `source` file.
@param {String} source the source path
@param {String} target the target path
@throws Error
@example // Moves file from a temporary upload directory into /var/www
fs.move('/tmp/uploads/fileA.txt', '/var/www/fileA.txt'); | exports.move ( source , target ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const remove = exports.remove = function(path) {
const nioPath = resolvePath(path);
if (Files.isDirectory(nioPath)) {
throw new Error(path + " is not a file");
}
Files.delete(nioPath);
} | Remove a file at the given `path`. Throws an error if `path` is not a file
or a symbolic link to a file.
@param {String} path the path of the file to remove.
@throws Error if path is not a file or could not be removed. | exports.remove ( path ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const exists = exports.exists = function(path) {
return Files.exists(resolvePath(path));
} | Return true if the file denoted by `path` exists, false otherwise.
@param {String} path the file path. | exports.exists ( path ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const workingDirectory = exports.workingDirectory = function() {
return resolvePath(java.lang.System.getProperty('user.dir')) + SEPARATOR;
} | Return the path name of the current working directory.
@returns {String} the current working directory | exports.workingDirectory ( ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const removeDirectory = exports.removeDirectory = function(path) {
Files.delete(resolvePath(path));
} | Remove a file or directory identified by `path`. Throws an error if
`path` is a directory and not empty.
@param {String} path the directory path
@throws Error if the file or directory could not be removed. | exports.removeDirectory ( path ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const list = exports.list = function(path) {
const nioPath = resolvePath(path);
if (!Files.isDirectory(nioPath)) {
throw new Error("failed to list directory " + path);
}
const files = [];
const dirStream = Files.newDirectoryStream(nioPath);
const dirIterator = dirStream.iterator();
while (dirIterator.hasNext()) {
files.push(String(dirIterator.next().getFileName()));
}
dirStream.close();
return files;
} | Returns an array of strings naming the files and directories in
the given directory. There is no guarantee that the strings are in
any specific order.
@example const names = fs.list('/usr/local/');
names.forEach(function(name) {
const fullPath = fs.join(dir, name);
if (fs.isFile(fullPath)) {
// do something with the file
}
});
@param {String} path the directory path
@returns {Array} an array of strings with the files, directories, or symbolic links | exports.list ( path ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const size = exports.size = function(path) {
const nioPath = resolvePath(path);
if (!Files.isRegularFile(nioPath)) {
throw new Error(path + " is not a file");
}
return Files.size(nioPath);
} | Returns the size of a file in bytes, or throws an exception if the path does
not correspond to an accessible path, or is not a regular file or a link.
@param {String} path the file path
@returns {Number} the file size in bytes
@throws Error if path is not a file | exports.size ( path ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const lastModified = exports.lastModified = function(path) {
const nioPath = resolvePath(path);
const fileTime = Files.getLastModifiedTime(nioPath);
return new Date(fileTime.toMillis());
} | Returns the time a file was last modified as a Date object.
@param {String} path the file path
@returns {Date} the date the file was last modified | exports.lastModified ( path ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const makeDirectory = exports.makeDirectory = function(path, permissions) {
// single-argument Files.createDirectory() respects the current umask
if (permissions == null) {
Files.createDirectory(getPath(path));
} else {
Files.createDirectory(getPath(path), (new PosixPermissions(permissions)).toJavaFileAttribute());
}
} | Create a single directory specified by `path`. If the directory cannot be
created for any reason an error is thrown. This includes if the parent
directories of `path` are not present. If a `permissions` argument is passed
to this function it is used to create a Permissions instance which is
applied to the given path during directory creation.
@param {String} path the file path
@param {Number|String|java.util.Set<PosixFilePermission>} permissions optional the POSIX permissions | exports.makeDirectory ( path , permissions ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const isReadable = exports.isReadable = function(path) {
return Files.isReadable(resolvePath(path));
} | Returns true if the file specified by path exists and can be opened for reading.
@param {String} path the file path
@returns {Boolean} whether the file exists and is readable | exports.isReadable ( path ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const isWritable = exports.isWritable = function(path) {
return Files.isWritable(resolvePath(path));
} | Returns true if the file specified by path exists and can be opened for writing.
@param {String} path the file path
@returns {Boolean} whether the file exists and is writable | exports.isWritable ( path ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const isFile = exports.isFile = function(path) {
return Files.isRegularFile(resolvePath(path));
} | Returns true if the file specified by path exists and is a regular file.
@param {String} path the file path
@returns {Boolean} whether the file exists and is a file | exports.isFile ( path ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const isDirectory = exports.isDirectory = function(path) {
return Files.isDirectory(resolvePath(path));
} | Returns true if the file specified by path exists and is a directory.
@param {String} path the file path
@returns {Boolean} whether the file exists and is a directory | exports.isDirectory ( path ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const isLink = exports.isLink = function(path) {
return Files.isSymbolicLink(resolvePath(path));
} | Return true if target file is a symbolic link, false otherwise.
@param {String} path the file path
@returns {Boolean} true if the given file exists and is a symbolic link | exports.isLink ( path ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const same = exports.same = function(pathA, pathB) {
// make canonical to resolve symbolic links
const nioPathA = getPath(canonical(pathA));
const nioPathB = getPath(canonical(pathB));
return Files.isSameFile(nioPathA, nioPathB);
} | Returns whether two paths refer to the same storage (file or directory),
either by virtue of symbolic or hard links, such that modifying one would
modify the other.
@param {String} pathA the first path
@param {String} pathB the second path
@returns {Boolean} true iff the two paths locate the same file | exports.same ( pathA , pathB ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const sameFilesystem = exports.sameFilesystem = function(pathA, pathB) {
// make canonical to resolve symbolic links
const nioPathA = getPath(canonical(pathA));
const nioPathB = getPath(canonical(pathB));
return nioPathA.getFileSystem().equals(nioPathB.getFileSystem());
} | Returns whether two paths refer to an entity of the same file system.
@param {String} pathA the first path
@param {String} pathB the second path
@returns {Boolean} true if same file system, otherwise false | exports.sameFilesystem ( pathA , pathB ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const canonical = exports.canonical = function(path) {
return String(resolvePath(path).toRealPath().normalize());
} | Returns the canonical path to a given abstract path. Canonical paths are both
absolute and intrinsic, such that all paths that refer to a given file
(whether it exists or not) have the same corresponding canonical path.
@param {String} path a file path
@returns {String} the canonical path | exports.canonical ( path ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const touch = exports.touch = function(path, mtime) {
const nioPath = resolvePath(path);
if (!Files.exists(nioPath)) {
Files.createFile(nioPath);
} else {
Files.setLastModifiedTime(nioPath, FileTime.fromMillis(mtime || Date.now()));
}
return true;
} | Sets the modification time of a file or directory at a given path to a
specified time, or the current time. Creates an empty file at the given path
if no file or directory exists, using the default permissions.
@param {String} path the file path
@param {Date} mtime optional date | exports.touch ( path , mtime ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const symbolicLink = exports.symbolicLink = function(existing, link) {
return String(Files.createSymbolicLink(getPath(link), getPath(existing)));
} | Creates a symbolic link at the target path that refers to the source path.
The concrete implementation depends on the file system and the operating system.
@param {String} existing path to an existing file, therefore the target of the link
@param {String} link the link to create pointing to an existing path
@returns {String} the path to the symbolic link | exports.symbolicLink ( existing , link ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const hardLink = exports.hardLink = function(existing, link) {
return String(Files.createLink(getPath(link), getPath(existing)));
} | Creates a hard link at the target path that refers to the source path.
The concrete implementation depends on the file system and the operating system.
@param {String} existing path to an existing file, therefore the target of the link
@param {String} link the link to create pointing to an existing path
@returns {String} the path to the link | exports.hardLink ( existing , link ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const readLink = exports.readLink = function(path) {
// Throws an exception if there is no symbolic link at the given path or the link cannot be read.
if (!Files.isReadable(getPath(path))) {
throw new Error("Path " + path + " is not readable!");
}
return Files.readSymbolicLink(resolvePath(path)).toString();
} | Returns the immediate target of the symbolic link at the given `path`.
@param {String} path a file path | exports.readLink ( path ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const iterate = exports.iterate = function(path) {
return function*() {
for (let item of list(path)) {
yield item;
}
throw StopIteration;
}();
} | Returns a Rhino-specific generator that produces the file names of a directory.
There is no guarantee that the produced strings are in any specific order.
@param {String} path a directory path
@see <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators">MDN Iterators and Generators</a>
@example // Iterates over the current working directory
for (let name of fs.iterate(".")) {
console.log(name);
} | exports.iterate ( path ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const permissions = exports.permissions = function(path) {
return new PosixPermissions(Files.getPosixFilePermissions(getPath(path)));
} | Returns the POSIX file permissions for the given path, if the filesystem supports POSIX.
@param {String} path
@returns PosixFilePermission the POSIX permissions for the given path | exports.permissions ( path ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const owner = exports.owner = function(path) {
try {
return Files.getOwner(getPath(path)).getName();
} catch (error) {
// do nothing
}
return null;
} | Returns the username of the owner of the given file.
@param {String} path
@returns {String} the username of the owner, or null if not possible to determine | exports.owner ( path ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const group = exports.group = function(path) {
try {
const attributes = Files.getFileAttributeView(getPath(path), PosixFileAttributeView);
return attributes.readAttributes().group().getName();
} catch (error) {
// do nothing
}
return null;
} | Returns the group name for the given file.
@param {String} path
@returns {String} the group's name, or null if not possible to determine | exports.group ( path ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const changePermissions = exports.changePermissions = function(path, permissions) {
permissions = new PosixPermissions(permissions);
return Files.setPosixFilePermissions(getPath(path), permissions.toJavaPosixFilePermissionSet());
} | Changes the permissions of the specified file.
@param {String} path
@param {Number|String|java.util.Set<PosixFilePermission>} permissions the POSIX permissions | exports.changePermissions ( path , permissions ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const changeOwner = exports.changeOwner = function(path, user) {
const lookupService = FS.getUserPrincipalLookupService();
const userPrincipal = lookupService.lookupPrincipalByName(user);
return Files.setOwner(getPath(path), userPrincipal);
} | Changes the owner of the specified file.
@param {String} path
@param {String} owner the user name string | exports.changeOwner ( path , user ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const changeGroup = exports.changeGroup = function(path, group) {
const lookupService = FS.getUserPrincipalLookupService();
const groupPrincipal = lookupService.lookupPrincipalByGroupName(group);
const attributes = Files.getFileAttributeView(
getPath(path),
PosixFileAttributeView,
LinkOption.NOFOLLOW_LINKS
);
attributes.setGroup(groupPrincipal);
return true;
} | Changes the group of the specified file.
@param {String} path
@param {String} group group name string | exports.changeGroup ( path , group ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const applyMode = function(mode) {
const options = {};
for (let i = 0; i < mode.length; i++) {
switch (mode[i]) {
case 'r':
options.read = true;
break;
case 'w':
options.write = true;
break;
case 'a':
options.append = true;
break;
case '+':
options.update = true;
break;
case 'b':
options.binary = true;
break;
case 'x':
// FIXME botic: is this implemented?
options.exclusive = true;
break;
case 'c':
// FIXME botic: is this needed?
options.canonical = true;
break;
default:
throw new Error("unsupported mode argument: " + options);
}
}
return options;
} | Internal. Convert a mode string to an options object. | applyMode ( mode ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const path = exports.path = function() {
return new Path(join.apply(null, arguments));
} | A shorthand for creating a new `Path` without the `new` keyword. | exports.path ( ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
Path.prototype.valueOf = function() {
return this.toString();
}; | This is a non-standard extension, not part of CommonJS Filesystem/A. | Path.prototype.valueOf ( ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
Path.prototype.to = function(target) {
return exports.Path(relative(this.toString(), target));
}; | Return the relative path from this path to the given target path. Equivalent
to `fs.Path(fs.relative(this, target))`.
@param {String} target | Path.prototype.to ( target ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
Path.prototype.from = function(target) {
return exports.Path(relative(target, this.toString()));
}; | Return the relative path from the given source path to this path. Equivalent
to `fs.Path(fs.relative(source, this))`.
@param {String} target | Path.prototype.from ( target ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
Path.prototype.listPaths = function() {
return this.list().map(file => new Path(this, file), this).sort();
}; | Return the names of all files in this path, in lexically sorted order and
wrapped in Path objects. | Path.prototype.listPaths ( ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const Path = exports.Path = function() {
if (!(this instanceof Path)) {
return new Path(join.apply(null, arguments));
}
const path = join.apply(null, arguments);
this.toString = () => path;
return this;
}
/** @ignore */
Path.prototype = Object.create(String.prototype);
Path.prototype.constructor = Path;
/**
* This is a non-standard extension, not part of CommonJS Filesystem/A.
*/
Path.prototype.valueOf = function() {
return this.toString();
};
/**
* Join a list of paths to this path.
*/
Path.prototype.join = function() {
return new Path(join.apply(null,
[this.toString()].concat(Array.prototype.slice.call(arguments))));
};
/**
* Resolve against this path.
*/
Path.prototype.resolve = function() {
return new Path(resolve.apply(
null,
[this.toString()].concat(Array.prototype.slice.call(arguments))
)
);
};
/**
* Return the relative path from this path to the given target path. Equivalent
* to `fs.Path(fs.relative(this, target))`.
* @param {String} target
*/
Path.prototype.to = function(target) {
return exports.Path(relative(this.toString(), target));
};
/**
* Return the relative path from the given source path to this path. Equivalent
* to `fs.Path(fs.relative(source, this))`.
* @param {String} target
*/
Path.prototype.from = function(target) {
return exports.Path(relative(target, this.toString()));
};
/**
* Return the names of all files in this path, in lexically sorted order and
* wrapped in Path objects.
*/
Path.prototype.listPaths = function() {
return this.list().map(file => new Path(this, file), this).sort();
};
const PATHED = [
'absolute',
'base',
'canonical',
'directory',
'normal',
'relative'
];
PATHED.forEach(name => {
Path.prototype[name] = function() {
return new Path(exports[name].apply(
this,
[this.toString()].concat(Array.prototype.slice.call(arguments))
));
};
});
const TRIVIA = [
'copy',
'copyTree',
'exists',
'extension',
'getAttributes',
'isDirectory',
'isFile',
'isLink',
'isReadable',
'isWritable',
'iterate',
'lastModified',
'link',
'list',
'listDirectoryTree',
'listTree',
'makeDirectory',
'makeTree',
'move',
'open',
'read',
'remove',
'removeTree',
'rename',
'size',
'split',
'symbolicLink',
'touch',
'write'
];
TRIVIA.forEach(name => {
Path.prototype[name] = function() {
const fn = exports[name];
if (!fn) {
throw new Error("Not found: " + name);
}
const result = fn.apply(
this,
[this.toString()].concat(Array.prototype.slice.call(arguments))
);
return result === undefined ? this : result;
};
}); | Path constructor. Path is a chainable shorthand for working with paths.
@augments String | exports.Path ( ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
exports.toByteArray = (str, charset) => {
if (typeof str !== "string" && !(str instanceof Binary)) {
throw new Error("'str' must be a string or instance of Binary.");
}
const appliedCharset = charset || 'utf8';
return str instanceof Binary
? str.toByteArray(appliedCharset, appliedCharset)
: new ByteArray(str, appliedCharset);
}; | Converts a String or Binary instance to a mutable ByteArray using the specified encoding.
@param {String|Binary} str The String or Binary to convert into a ByteArray
@param {String} charset the string's encoding. Defaults to 'UTF-8'
@returns {ByteArray} a ByteArray representing the str
@example const binary = require("binary");
const ba = binary.toByteArray("hello world"); | exports.toByteArray | javascript | ringo/ringojs | modules/binary.js | https://github.com/ringo/ringojs/blob/master/modules/binary.js | Apache-2.0 |
exports.toByteString = (str, charset) => {
if (typeof str !== "string" && !(str instanceof Binary)) {
throw new Error("'str' must be a string or instance of Binary.");
}
const appliedCharset = charset || 'utf8';
return str instanceof Binary
? str.toByteString(appliedCharset, appliedCharset)
: ByteString(str, appliedCharset);
}; | Converts a String or Binary instance to an immutable ByteString using the specified encoding.
@param {String|Binary} str A String or Binary to convert into a ByteString
@param {String} charset the string's encoding. Defaults to 'UTF-8'
@returns {ByteString} a ByteString representing str
@example const binary = require("binary");
const bs = binary.toByteString("hello world"); | exports.toByteString | javascript | ringo/ringojs | modules/binary.js | https://github.com/ringo/ringojs/blob/master/modules/binary.js | Apache-2.0 |
this.connect = function(host, port, timeout) {
const address = toSocketAddress(host, port);
if (arguments.length < 3) {
socket.connect(address);
} else {
socket.connect(address, timeout);
}
return this;
}; | Initiate a connection on a socket. Connect to a remote port on the specified
host with a connection timeout. Throws an exception in case of failure.
@param {String} host IP address or hostname
@param {Number} port port number or service name
@param {Number} [timeout] optional timeout value in milliseconds | this.connect ( host , port , timeout ) | javascript | ringo/ringojs | modules/net.js | https://github.com/ringo/ringojs/blob/master/modules/net.js | Apache-2.0 |
this.bind = function(host, port) {
const address = toSocketAddress(host, port);
socket.bind(address);
return this;
}; | Binds the socket to a local address and port. If address or port are
omitted the system will choose a local address and port to bind the socket.
@param {String} host address (interface) to which the socket will be bound.
@param {Number} port port number to bind the socket to. | this.bind ( host , port ) | javascript | ringo/ringojs | modules/net.js | https://github.com/ringo/ringojs/blob/master/modules/net.js | Apache-2.0 |
this.getStream = function() {
if(!stream) {
if (!socket.isConnected()) {
throw new Error("Socket is not connected");
}
stream = new io.Stream(socket.inputStream, socket.outputStream);
}
return stream;
}; | Get the [I/O stream](../io#Stream) for this socket.
@return {Stream} a binary stream
@see io#Stream | this.getStream ( ) | javascript | ringo/ringojs | modules/net.js | https://github.com/ringo/ringojs/blob/master/modules/net.js | Apache-2.0 |
this.isBound = function() {
return socket.isBound();
}; | Returns whether this socket is bound to an address.
@return true if the socket has been bound to an address | this.isBound ( ) | javascript | ringo/ringojs | modules/net.js | https://github.com/ringo/ringojs/blob/master/modules/net.js | Apache-2.0 |
this.isConnected = function() {
return socket.isConnected();
}; | Returns whether the socket is connected or not.
@return true if the socket has been connected to a remote address | this.isConnected ( ) | javascript | ringo/ringojs | modules/net.js | https://github.com/ringo/ringojs/blob/master/modules/net.js | Apache-2.0 |
this.isClosed = function() {
return socket.isClosed();
}; | Returns whether the socket is closed or not.
@return true if the socket has been closed | this.isClosed ( ) | javascript | ringo/ringojs | modules/net.js | https://github.com/ringo/ringojs/blob/master/modules/net.js | Apache-2.0 |
this.getTimeout = function() {
return socket.getSoTimeout();
}; | Return the current timeout of this Socket. A value of zero
implies that timeout is disabled, i.e. read() will never time out.
@return {Number} the current timeout | this.getTimeout ( ) | javascript | ringo/ringojs | modules/net.js | https://github.com/ringo/ringojs/blob/master/modules/net.js | Apache-2.0 |
this.setTimeout = function(timeout) {
socket.setSoTimeout(timeout);
}; | Enable/disable timeout with the specified timeout, in milliseconds.
With this option set to a non-zero timeout, a read() on this socket's
stream will block for only this amount of time.
@param {Number} timeout timeout in milliseconds | this.setTimeout ( timeout ) | javascript | ringo/ringojs | modules/net.js | https://github.com/ringo/ringojs/blob/master/modules/net.js | Apache-2.0 |
this.connect = function(host, port) {
const address = toSocketAddress(host, port);
socket.connect(address);
return this;
}; | Connect the socket to a remote address. If a DatagramSocket is connected,
it may only send data to and receive data from the given address. By
default DatagramSockets are not connected.
@param {String} host IP address or hostname
@param {Number} port port number or service name | this.connect ( host , port ) | javascript | ringo/ringojs | modules/net.js | https://github.com/ringo/ringojs/blob/master/modules/net.js | Apache-2.0 |
this.receive = function(length, buffer) {
const packet = receiveInternal(length, buffer);
buffer = binary.ByteArray.wrap(packet.getData());
buffer.length = packet.length;
return buffer;
}; | Receive a datagram packet from this socket. This method does not return
the sender's IP address, so it is meant to be in conjunction with
[connect()](#DatagramSocket.prototype.connect).
@param {Number} length the maximum number of bytes to receive
@param {ByteArray} buffer optional buffer to store bytes in
@return {ByteArray} the received data | this.receive ( length , buffer ) | javascript | ringo/ringojs | modules/net.js | https://github.com/ringo/ringojs/blob/master/modules/net.js | Apache-2.0 |
this.send = function(data) {
socket.send(toDatagramPacket(data));
}; | Send a datagram packet from this socket. This method does not allow
the specify the recipient's IP address, so it is meant to be in
conjunction with [connect()](#DatagramSocket.prototype.connect).
@param {Binary} data the data to send | this.send ( data ) | javascript | ringo/ringojs | modules/net.js | https://github.com/ringo/ringojs/blob/master/modules/net.js | Apache-2.0 |
this.sendTo = function(host, port, data) {
const packet = toDatagramPacket(data);
packet.setSocketAddress(toSocketAddress(host, port));
socket.send(packet);
} | Send a datagram packet from this socket to the specified address.
@param {String} host the IP address of the recipient
@param {Number} port the port number
@param {Binary} data the data to send | this.sendTo ( host , port , data ) | javascript | ringo/ringojs | modules/net.js | https://github.com/ringo/ringojs/blob/master/modules/net.js | Apache-2.0 |
this.accept = function() {
return new Socket(socket.accept());
}; | Listens for a connection to be made to this socket and returns a new
[Socket](#Socket) object. The method blocks until a connection is made.
@return {Socket} a newly connected socket object | this.accept ( ) | javascript | ringo/ringojs | modules/net.js | https://github.com/ringo/ringojs/blob/master/modules/net.js | Apache-2.0 |
const evalArguments = (args, argsExpected) => {
if (!(args.length === argsExpected ||
(args.length === argsExpected + 1 && getType(args[args.length - 1]) === "string"))) {
throw new ArgumentsError("Insufficient arguments passed to assertion function");
}
return args[argsExpected];
}; | @param {Object} args The arguments array.
@param {Number} argsExpected The number of expected arguments
@returns The comment appended to the expected arguments, if any
@type String | evalArguments | javascript | ringo/ringojs | modules/assert.js | https://github.com/ringo/ringojs/blob/master/modules/assert.js | Apache-2.0 |
const isDeepEqual = (value1, value2) => {
if (value1 === value2) {
return true;
} else if (value1 instanceof Date && value2 instanceof Date) {
return value1.getTime() === value2.getTime();
} else if (typeof(value1) != "object" || typeof(value2) != "object") {
return value1 == value2;
} else {
return objectsAreEqual(value1, value2);
}
} | Deep-compares both arguments.
@param {Object} value1 The argument to be compared
@param {Object} value2 The argument to be compared to
@returns True if arguments are equal, false otherwise
@type Boolean | isDeepEqual | javascript | ringo/ringojs | modules/assert.js | https://github.com/ringo/ringojs/blob/master/modules/assert.js | Apache-2.0 |
const objectsAreEqual = (obj1, obj2) => {
if (isNullOrUndefined(obj1) || isNullOrUndefined(obj2)) {
return false;
}
// the 1.0 spec (and Unittest/B) speaks of comparing the prototype
// property, which is only set for constructor functions (for instances
// it's undefined). plus only owned properties are compared, leading
// to two objects being equivalent even if their prototypes have
// different properties. instead using Object.getPrototypeOf()
// to compare the prototypes of two objects
// see also http://groups.google.com/group/commonjs/msg/501a7e3cd9a920e5
if (Object.getPrototypeOf(obj1) !== Object.getPrototypeOf(obj2)) {
return false;
}
// compare object keys (objects *and* arrays)
const keys1 = getOwnKeys(obj1);
const keys2 = getOwnKeys(obj2);
const propsAreEqual = keys1.length === keys2.length && keys1.every(function(name, idx) {
return name === keys2[idx] && isDeepEqual(obj1[name], obj2[name]);
});
if (propsAreEqual === false) {
return propsAreEqual;
}
// array comparison
if (getType(obj1) === "array") {
return obj1.length === obj2.length && obj1.every(function(value, idx) {
return isDeepEqual(value, obj2[idx]);
});
}
return true;
}; | Returns true if the objects passed as argument are equal
@param {Object} obj1 The object to be compared
@param {Object} obj2 The object to be compared to
@returns True if the objects are equal, false otherwise
@type Boolean | objectsAreEqual | javascript | ringo/ringojs | modules/assert.js | https://github.com/ringo/ringojs/blob/master/modules/assert.js | Apache-2.0 |
const isNullOrUndefined = (obj) => {
return obj === null || obj === undefined;
}; | Returns true if the argument is null or undefined
@param {Object} obj The object to test
@returns True if the argument is null or undefined
@type Boolean | isNullOrUndefined | javascript | ringo/ringojs | modules/assert.js | https://github.com/ringo/ringojs/blob/master/modules/assert.js | Apache-2.0 |
const getOwnKeys = (obj) => {
return Object.keys(obj).sort();
}; | Returns the names of owned properties of the object passed as argument.
Note that this only includes those properties for which hasOwnProperty
returns true
@param {Object} obj The object to return its propery names for
@returns The property names
@type Array | getOwnKeys | javascript | ringo/ringojs | modules/assert.js | https://github.com/ringo/ringojs/blob/master/modules/assert.js | Apache-2.0 |
const fail = exports.fail = function fail(options) {
throw new AssertionError(options);
}; | Basic failure method. Fails an assertion without checking any preconditions.
@param {Object|String} options An object containing optional "message", "actual"
and "expected" properties, or alternatively a message string
@throws AssertionError
@example // a complex condition
if (a === true && (b === "complex" || ...)) {
assert.fail("This should not be reached!");
} | fail ( options ) | javascript | ringo/ringojs | modules/assert.js | https://github.com/ringo/ringojs/blob/master/modules/assert.js | Apache-2.0 |
const prependComment = (message, comment) => {
if (getType(comment) === "string" && comment.length > 0) {
return comment + "\n" + message;
}
return message;
}; | Prepends the comment to the message, if given
@returns The message
@type String | prependComment | javascript | ringo/ringojs | modules/assert.js | https://github.com/ringo/ringojs/blob/master/modules/assert.js | Apache-2.0 |
exports.stringContains = function stringContains(value, pattern) {
const comment = evalArguments(arguments, arguments.callee.length);
if (getType(pattern) === "string") {
if (value.indexOf(pattern) < 0) {
fail(prependComment("Expected string " + jsDump(pattern) +
" to be found in " + jsDump(value), comment));
}
} else {
throw new ArgumentsError("Invalid argument to assertStringContains(string, string):\n" +
jsDump(pattern));
}
} | Checks if the value passed as argument contains the pattern specified.
@example assert.stringContains("this will pass", "pass");
assert.stringContains("this will fail", "pass");
@param {String} value The string that should contain the pattern
@param {String} pattern The string that should be contained
@throws ArgumentsError
@throws AssertionError | stringContains ( value , pattern ) | javascript | ringo/ringojs | modules/assert.js | https://github.com/ringo/ringojs/blob/master/modules/assert.js | Apache-2.0 |
exports.matches = function matches(value, expr) {
const comment = evalArguments(arguments, arguments.callee.length);
if (getType(expr) === "regexp") {
if (expr.test(value) === false) {
fail(prependComment("Expected pattern " + jsDump(expr) + " to match " +
jsDump(value), comment));
}
} else {
throw new ArgumentsError("Invalid argument to assertMatch(string, regexp):\n" +
jsDump(expr));
}
} | Checks if the regular expression matches the string.
@example assert.matches("this will pass", /p.?[s]{2}/);
assert.matches("this will fail", /[0-9]+/);
@param {String} value The string that should contain the regular expression pattern
@param {RegExp} expr The regular expression that should match the value
@throws ArgumentsError
@throws AssertionError | matches ( value , expr ) | javascript | ringo/ringojs | modules/assert.js | https://github.com/ringo/ringojs/blob/master/modules/assert.js | Apache-2.0 |
exports.log = function() {
writer.writeln(format.apply(null, arguments));
}; | Logs a message to the console on <code>stdout</code>.
The first argument to log may be a string containing printf-like placeholders.
Otherwise, multipel arguments will be concatenated separated by spaces.
@param {*...} msg... one or more message arguments
@example >> console.log('Hello World!');
Hello World!
>> console.log('A: %s, B: %s, C: %s', 'a', 'b', 'c');
A: a, B: b, C: c
>> console.log('Current nanoseconds: %d', java.lang.System.nanoTime());
Current nanoseconds: 9607196939209 | exports.log ( ) | javascript | ringo/ringojs | modules/console.js | https://github.com/ringo/ringojs/blob/master/modules/console.js | Apache-2.0 |
exports.error = traceHelper.bind(null, function() {
const msg = format.apply(null, arguments);
const location = format("(%s:%d)", this.sourceName(), this.lineNumber());
errWriter.writeln(ONRED, BOLD, "[error]" + RESET, BOLD, msg, RESET, location);
}); | Logs a message with the visual "error" representation, including the file name
and line number of the calling code. Prints on <code>stderr</code>.
@param {*...} msg... one or more message arguments
@function
@example >> console.error('Hello World!');
[error] Hello World! (<stdin>:1)
>> console.error('A: %s, B: %s, C: %s', 'a', 'b', 'c');
[error] A: a, B: b, C: c (<stdin>:3)
>> console.error('Current nanoseconds: %d', java.lang.System.nanoTime());
[error] Current nanoseconds: 9228448561643 (<stdin>:5) | (anonymous) ( ) | javascript | ringo/ringojs | modules/console.js | https://github.com/ringo/ringojs/blob/master/modules/console.js | Apache-2.0 |
exports.warn = traceHelper.bind(null, function() {
const msg = format.apply(null, arguments);
const location = format("(%s:%d)", this.sourceName(), this.lineNumber());
errWriter.writeln(ONYELLOW, BOLD, "[warn]" + RESET, BOLD, msg, RESET, location);
}); | Logs a message with the visual "warn" representation, including the file name
and line number of the calling code. Prints on <code>stderr</code>.
@param {*...} msg... one or more message arguments
@function
@example >> console.warn('Hello World!');
[warn] Hello World! (<stdin>:1)
>> console.warn('A: %s, B: %s, C: %s', 'a', 'b', 'c');
[warn] A: a, B: b, C: c (<stdin>:3)
>> console.warn('Current nanoseconds: %d', java.lang.System.nanoTime());
[warn] Current nanoseconds: 9294672097821 (<stdin>:5) | (anonymous) ( ) | javascript | ringo/ringojs | modules/console.js | https://github.com/ringo/ringojs/blob/master/modules/console.js | Apache-2.0 |
exports.info = traceHelper.bind(null, function() {
const msg = format.apply(null, arguments);
const location = format("(%s:%d)", this.sourceName(), this.lineNumber());
writer.writeln("[info]", BOLD, msg, RESET, location);
}); | Logs a message with the visual "info" representation, including the file name
and line number of the calling code. Prints on <code>stdout</code>.
@param {*...} msg... one or more message arguments
@function
@example >> console.info('Hello World!');
[info] Hello World! (<stdin>:1)
>> console.info('A: %s, B: %s, C: %s', 'a', 'b', 'c');
[info] A: a, B: b, C: c (<stdin>:3)
>> console.info('Current nanoseconds: %d', java.lang.System.nanoTime());
[info] Current nanoseconds: 9677228481391 (<stdin>:5) | (anonymous) ( ) | javascript | ringo/ringojs | modules/console.js | https://github.com/ringo/ringojs/blob/master/modules/console.js | Apache-2.0 |
exports.trace = traceHelper.bind(null, function() {
const msg = format.apply(null, arguments);
writer.writeln("Trace: " + msg);
writer.write(this.scriptStackTrace);
}); | Prints a stack trace of JavaScript execution at the point where it is called.
Prints on <code>stdout</code>.
@param {*...} msg... optional message arguments
@function | (anonymous) ( ) | javascript | ringo/ringojs | modules/console.js | https://github.com/ringo/ringojs/blob/master/modules/console.js | Apache-2.0 |
exports.time = function(name) {
if (name && !timers[name]) {
timers[name] = java.lang.System.nanoTime();
}
}; | Creates a new timer under the given name. Call `console.timeEnd(name)` with
the same name to stop the timer and log the time elapsed.
@param {String} name the timer name
@example >> console.time('timer-1');
>> // Wait some time ...
>> console.timeEnd('timer-1');
timer-1: 15769ms | exports.time ( name ) | javascript | ringo/ringojs | modules/console.js | https://github.com/ringo/ringojs/blob/master/modules/console.js | Apache-2.0 |
exports.timeEnd = function(name) {
const start = timers[name];
if (start) {
const time = Math.round((java.lang.System.nanoTime() - start) / 1000000);
writer.writeln(name + ": " + time + "ms");
delete timers[name];
return time;
}
}; | Stops a timer created by a call to `console.time(name)` and logs the time elapsed.
@param {String} name the timer name
@example >> console.time('timer-1');
>> // Wait some time ...
>> console.timeEnd('timer-1');
timer-1: 15769ms | exports.timeEnd ( name ) | javascript | ringo/ringojs | modules/console.js | https://github.com/ringo/ringojs/blob/master/modules/console.js | Apache-2.0 |
exports.dir = function(obj) {
require("ringo/shell").printResult(obj, writer);
}; | Prints a list of all properties of an object on <code>stdout</code>.
@param {Object} obj the object whose properties should be output
@example >> const obj = { foo: "bar", baz: 12345 };
>> console.dir(obj);
{ foo: 'bar', baz: 12345 } | exports.dir ( obj ) | javascript | ringo/ringojs | modules/console.js | https://github.com/ringo/ringojs/blob/master/modules/console.js | Apache-2.0 |
this.open = (name) => {
return new io.Stream(zipfile.getInputStream(getEntry(name)));
}; | Get an input stream to read the entry with the given name.
@param {String} name the entry name | this.open | javascript | ringo/ringojs | modules/ringo/zip.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/zip.js | Apache-2.0 |
this.isDirectory = (name) => {
const entry = map[name];
return entry && entry.isDirectory();
}; | Returns true if the entry with the given name represents a directory.
@param {String} name the entry name | this.isDirectory | javascript | ringo/ringojs | modules/ringo/zip.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/zip.js | Apache-2.0 |
this.isFile = (name) => {
const entry = map[name];
return entry && !entry.isDirectory();
}; | Returns true if the entry with the given name represents a file.
@param {String} name the entry name | this.isFile | javascript | ringo/ringojs | modules/ringo/zip.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/zip.js | Apache-2.0 |
this.getSize = (name) => {
return getEntry(name).getSize();
}; | Returns the uncompressed size in bytes in the given entry, or -1 if not known.
@param {String} name the entry name | this.getSize | javascript | ringo/ringojs | modules/ringo/zip.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/zip.js | Apache-2.0 |
this.getTime = (name) => {
return getEntry(name).getTime();
}; | Returns the last modification timestamp of the given entry, or -1 if not available.
@param {String} name the entry name | this.getTime | javascript | ringo/ringojs | modules/ringo/zip.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/zip.js | Apache-2.0 |
exports.init = () => {
log.info("init", system.args);
// Remove our own script name from args
system.args.shift();
if (system.args.length) {
const appId = system.args[0];
try {
app = require(appId);
} catch (error) {
log.error("Error loading application module '" + appId + "'");
log.error(error);
}
} else {
log.error("No application module defined in command line arguments")
}
if (app && typeof app.init === "function") {
app.init();
}
}; | Called when the daemon instance is created.
This function can be run with superuser id to perform privileged actions
before the daemon is started. | exports.init | javascript | ringo/ringojs | modules/ringo/daemon.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/daemon.js | Apache-2.0 |
exports.start = () => {
log.info("start");
if (app && typeof app.start === "function") {
app.start();
}
}; | Called when the daemon instance is started. | exports.start | javascript | ringo/ringojs | modules/ringo/daemon.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/daemon.js | Apache-2.0 |
exports.destroy = () => {
log.info("destroy");
if (app && typeof app.destroy === "function") {
app.destroy();
}
}; | Called when the daemon is destroyed. | exports.destroy | javascript | ringo/ringojs | modules/ringo/daemon.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/daemon.js | Apache-2.0 |
this.terminate = function() {
if (worker) {
worker.release();
worker = null;
}
}; | Release the worker, returning it to the engine's worker pool.
Note that this does not terminate the worker thread, or remove any
current or future scheduled tasks from its event loop. | this.terminate ( ) | javascript | ringo/ringojs | modules/ringo/worker.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/worker.js | Apache-2.0 |
connect: (input, output, errput) => {
if (input) {
spawn(function() {
input.copy(stdin);
}).get();
}
spawn(function() {
stdout.copy(output);
}).get();
spawn(function() {
stderr.copy(errput);
}).get();
} | Connects the process's steams to the argument streams and starts threads to
copy the data asynchronously.
@param {Stream} input output stream to connect to the process's input stream
@param {Stream} output input stream to connect to the process's output stream
@param {Stream} errput input stream to connect to the process's error stream
@name Process.prototype.connect | connect | javascript | ringo/ringojs | modules/ringo/subprocess.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/subprocess.js | Apache-2.0 |
exports.command = function() {
const args = parseArguments(arguments);
const process = createProcess(args);
let output= new io.MemoryStream();
let errput = new io.MemoryStream();
if (!args.binary) {
output = new io.TextStream(output, {charset: args.encoding});
errput = new io.TextStream(errput, {charset: args.encoding});
}
process.connect(null, output, errput);
const status = process.wait();
if (status !== 0) {
throw new Error("(" + status + ") " + errput.content);
}
return output.content;
}; | Executes a given command and returns the standard output.
If the exit status is non-zero, throws an Error. Examples:
<pre><code>const {command} = require("ringo/subprocess");<br>
// get PATH environment variable on Unix-like systems
const path = command("/bin/bash", "-c", "echo $PATH");<br>
// a simple ping
const result = command("ping", "-c 1", "ringojs.org");
</code></pre>
@param {String} command command to call in the runtime environment
@param {String} [arguments...] optional arguments as single or multiple string parameters.
Each argument is analogous to a quoted argument on the command line.
@param {Object} [options] options object. This may contain a `dir` string
property specifying the directory to run the process in and a `env`
object property specifying additional environment variable mappings.
@returns {String} the standard output of the command | exports.command ( ) | javascript | ringo/ringojs | modules/ringo/subprocess.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/subprocess.js | Apache-2.0 |
exports.system = function() {
const args = parseArguments(arguments);
const process = createProcess(args);
let output = system.stdout;
let errput = system.stderr;
if (args.binary) {
output = output.raw;
errput = errput.raw;
}
process.connect(null, output, errput);
return process.wait();
}; | Executes a given command, attached to the JVM process's
output and error streams <code>System.stdout</code> and <code>System.stderr</code>,
and returns the exit status.
@param {String} command command to call in the runtime environment
@param {String} [arguments...] optional arguments as single or multiple string parameters.
Each argument is analogous to a quoted argument on the command line.
@param {Object} [options] options object. This may contain a `dir` string
property specifying the directory to run the process in and a `env`
object property specifying additional environment variable mappings.
@returns {Number} exit status | exports.system ( ) | javascript | ringo/ringojs | modules/ringo/subprocess.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/subprocess.js | Apache-2.0 |
exports.status = function() {
const process = createProcess(parseArguments(arguments));
process.connect(null, new DummyStream(), new DummyStream());
return process.wait();
}; | Executes a given command quietly and returns the exit status.
@param {String} command command to call in the runtime environment
@param {String} [arguments...] optional arguments as single or multiple string parameters.
Each argument is analogous to a quoted argument on the command line.
@param {Object} [options] options object. This may contain a `dir` string
property specifying the directory to run the process in and a `env`
object property specifying additional environment variable mappings.
@returns {Number} exit status
@name status | exports.status ( ) | javascript | ringo/ringojs | modules/ringo/subprocess.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/subprocess.js | Apache-2.0 |
this.addOption = function(shortName, longName, argument, helpText) {
if (typeof(shortName) === "string" && shortName.length !== 1) {
throw new Error("Short option must be a string of length 1");
}
longName = longName || "";
argument = argument || "";
options.push({
shortName: shortName,
longName: longName,
argument: argument,
helpText: helpText
});
return this;
}; | Add an option to the parser.
@param {String} shortName the short option name (without leading hyphen)
@param {String} longName the long option name (without leading hyphens)
@param {String} argument display name of the option's value, or null if the argument is a singular switch
@param {String} helpText the help text to display for the option
@returns {Object} this parser for chained invocation | this.addOption ( shortName , longName , argument , helpText ) | javascript | ringo/ringojs | modules/ringo/args.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/args.js | Apache-2.0 |
this.help = function() {
const lines = options.reduce((lines, opt) => {
let flags;
if (opt.shortName !== undefined && opt.shortName !== null) {
flags = " -" + opt.shortName;
} else {
flags = " ";
}
if (opt.longName) {
flags += " --" + opt.longName;
}
if (opt.argument) {
flags += " " + opt.argument;
}
lines.push({flags: flags, helpText: opt.helpText});
return lines;
}, []);
const maxlength = lines.reduce((prev, val) => Math.max(val.flags.length, prev), 0);
return lines.map(s => {
return strings.pad(s.flags, " ", 2 + maxlength) + s.helpText;
}).join("\n");
}; | Get help text for the parser's options suitable for display in command line scripts.
@returns {String} a string explaining the parser's options | this.help ( ) | javascript | ringo/ringojs | modules/ringo/args.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/args.js | Apache-2.0 |
this.parse = function(args, result) {
result || (result = {});
while (args.length > 0) {
let option = args[0];
if (!strings.startsWith(option, "-")) {
break;
}
if (strings.startsWith(option, "--")) {
parseLongOption(options, option.substring(2), args, result);
} else {
parseShortOption(options, option.substring(1), args, result);
}
}
return result;
}; | Parse an arguments array into an option object. If a long option name is defined,
it is converted to camel-case and used as property name. Otherwise, the short option
name is used as property name.
Passing an result object as second argument is a convenient way to define default
options:
@param {Array} args the argument array. Matching options are removed.
@param {Object} result optional result object. If undefined, a new Object is created.
@returns {Object} the result object
@see <a href="../../ringo/utils/strings/index.html#toCamelCase">toCamelCase()</a>
@example parser.parse(system.args.slice(1), {myOption: "defaultValue"}); | this.parse ( args , result ) | javascript | ringo/ringojs | modules/ringo/args.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/args.js | Apache-2.0 |
exports.Parser = function() {
const options = [];
/**
* Add an option to the parser.
* @param {String} shortName the short option name (without leading hyphen)
* @param {String} longName the long option name (without leading hyphens)
* @param {String} argument display name of the option's value, or null if the argument is a singular switch
* @param {String} helpText the help text to display for the option
* @returns {Object} this parser for chained invocation
*/
this.addOption = function(shortName, longName, argument, helpText) {
if (typeof(shortName) === "string" && shortName.length !== 1) {
throw new Error("Short option must be a string of length 1");
}
longName = longName || "";
argument = argument || "";
options.push({
shortName: shortName,
longName: longName,
argument: argument,
helpText: helpText
});
return this;
};
/**
* Get help text for the parser's options suitable for display in command line scripts.
* @returns {String} a string explaining the parser's options
*/
this.help = function() {
const lines = options.reduce((lines, opt) => {
let flags;
if (opt.shortName !== undefined && opt.shortName !== null) {
flags = " -" + opt.shortName;
} else {
flags = " ";
}
if (opt.longName) {
flags += " --" + opt.longName;
}
if (opt.argument) {
flags += " " + opt.argument;
}
lines.push({flags: flags, helpText: opt.helpText});
return lines;
}, []);
const maxlength = lines.reduce((prev, val) => Math.max(val.flags.length, prev), 0);
return lines.map(s => {
return strings.pad(s.flags, " ", 2 + maxlength) + s.helpText;
}).join("\n");
};
/**
* Parse an arguments array into an option object. If a long option name is defined,
* it is converted to camel-case and used as property name. Otherwise, the short option
* name is used as property name.
*
* Passing an result object as second argument is a convenient way to define default
* options:
* @param {Array} args the argument array. Matching options are removed.
* @param {Object} result optional result object. If undefined, a new Object is created.
* @returns {Object} the result object
* @see <a href="../../ringo/utils/strings/index.html#toCamelCase">toCamelCase()</a>
* @example parser.parse(system.args.slice(1), {myOption: "defaultValue"});
*/
this.parse = function(args, result) {
result || (result = {});
while (args.length > 0) {
let option = args[0];
if (!strings.startsWith(option, "-")) {
break;
}
if (strings.startsWith(option, "--")) {
parseLongOption(options, option.substring(2), args, result);
} else {
parseShortOption(options, option.substring(1), args, result);
}
}
return result;
};
return this;
}; | Create a new command line option parser. | exports.Parser ( ) | javascript | ringo/ringojs | modules/ringo/args.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/args.js | Apache-2.0 |
const resolve = sync((result, isError) => {
if (state !== NEW) {
throw new Error("Promise has already been resolved.");
}
value = result;
state = isError ? FAILED : FULFILLED;
listeners.forEach(notify);
listeners = [];
lock.notifyAll();
}, lock); | Resolve the promise.
@name Deferred.prototype.resolve
@param {Object} result the result or error value
@param {Boolean} isError if true the promise is resolved as failed
@type Function | (anonymous) | javascript | ringo/ringojs | modules/ringo/promise.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/promise.js | Apache-2.0 |
then: sync((callback, errback) => {
if (typeof callback !== "function") {
throw new Error("First argument to then() must be a function.");
}
const tail = new Deferred();
const listener = {
tail: tail,
callback: callback,
errback: errback
};
if (state === NEW) {
listeners.push(listener);
} else {
notify(listener);
}
return tail.promise;
}, lock), | Register callback and errback functions to be invoked when
the promise is resolved.
@name Promise.prototype.then
@param {Function} callback called if the promise is resolved as fulfilled
@param {Function} errback called if the promise is resolved as failed
@return {Object} a new promise that resolves to the return value of the
callback or errback when it is called. | sync | javascript | ringo/ringojs | modules/ringo/promise.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/promise.js | Apache-2.0 |
exports.PromiseList = function PromiseList(args) {
const promises = Array.isArray(args) ? args : Array.prototype.slice.call(arguments);
const count = new java.util.concurrent.atomic.AtomicInteger(promises.length);
const results = [];
const deferred = new Deferred();
promises.forEach((promise, index) => {
if (typeof promise.then !== "function" && promise.promise) {
promise = promise.promise;
}
promise.then(
sync(value => {
results[index] = {value: value};
if (count.decrementAndGet() === 0) {
deferred.resolve(results);
}
}, count),
sync(error => {
results[index] = {error: error};
if (count.decrementAndGet() === 0) {
deferred.resolve(results);
}
}, count)
);
});
return deferred.promise;
}; | The PromiseList class allows to combine several promises into one.
It represents itself a promise that resolves to an array of objects,
each containing a `value` or `error` property with the value
or error of the corresponding promise argument.
A PromiseList resolves successfully even if some or all of the partial
promises resolve to an error. It is the responsibility of the handler
function to check each individual promise result.
@param {Promise...} promise... any number of promise arguments.
@constructor
@example
// --- sample output ---
// Done!
// { value: 'i am ok' }
// { value: 1 }
// { error: 'some error' }
let d1 = Deferred(), d2 = Deferred(), d3 = Deferred();
// PromiseList accepts a promise or deferred object
let list = PromiseList(d1.promise, d2, d3);
list.then(function(results) {
console.log("Done!");
results.forEach(function(result) {
console.dir(result);
});
}, function(error) {
console.error("Error :-(");
});
d2.resolve(1);
d3.resolve("some error", true);
d1.resolve("i am ok"); | PromiseList ( args ) | javascript | ringo/ringojs | modules/ringo/promise.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/promise.js | Apache-2.0 |
exports.properties = (() => {
try {
return new ScriptableMap(java.lang.System.getProperties());
} catch (error) {
return {};
}
})(); | An object reflecting the Java system properties. | (anonymous) | javascript | ringo/ringojs | modules/ringo/engine.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/engine.js | Apache-2.0 |
exports.addHostObject = (javaClass) => {
engine.defineHostClass(javaClass);
}; | Define a class as Rhino host object.
@param {JavaClass} javaClass the class to define as host object | exports.addHostObject | javascript | ringo/ringojs | modules/ringo/engine.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/engine.js | Apache-2.0 |
exports.addShutdownHook = (funcOrObject, sync) => {
engine.addShutdownHook(funcOrObject, Boolean(sync));
}; | Register a callback to be invoked when the current RingoJS instance is
terminated.
@param {Function|Object} funcOrObject Either a JavaScript function or a
JavaScript object containing properties called `module` and `name`
specifying a function exported by a RingoJS module.
@param {Boolean} sync (optional) whether to invoke the callback
synchronously (on the main shutdown thread) or asynchronously (on the
worker's event loop thread) | exports.addShutdownHook | javascript | ringo/ringojs | modules/ringo/engine.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/engine.js | Apache-2.0 |
exports.createSandbox = (modulePath, globals, options) => {
options || (options = {});
const systemModules = options.systemModules || null;
const config = new RingoConfig(engine.getRingoHome(), modulePath, systemModules);
if (options.classShutter) {
const shutter = options.shutter;
config.setClassShutter(shutter instanceof ClassShutter ?
shutter : new ClassShutter(shutter));
}
config.setSealed(Boolean(options.sealed));
return engine.createSandbox(config, globals);
}; | Create a sandboxed scripting engine with the same install directory as this and the
given module paths, global properties, class shutter and sealing
@param {Array} modulePath the comma separated module search path
@param {Object} globals a map of predefined global properties (may be undefined)
@param {Object} options an options object (may be undefined). The following options are supported:
- systemModules array of system module directories to add to the module search path
(may be relative to the ringo install dir)
- classShutter a Rhino class shutter, may be null
- sealed if the global object should be sealed, defaults to false
@returns {RhinoEngine} a sandboxed RhinoEngine instance
@throws {FileNotFoundException} if any part of the module paths does not exist | exports.createSandbox | javascript | ringo/ringojs | modules/ringo/engine.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/engine.js | Apache-2.0 |
exports.getRingoHome = () => engine.getRingoHome(); | Get the RingoJS installation directory.
@returns {Repository} a Repository representing the Ringo installation directory | exports.getRingoHome | javascript | ringo/ringojs | modules/ringo/engine.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/engine.js | Apache-2.0 |
exports.asJavaObject = (object) => engine.asJavaObject(object); | Get a wrapper for an object that exposes it as Java object to JavaScript.
@param {Object} object an object
@returns {Object} the object wrapped as native java object | exports.asJavaObject | javascript | ringo/ringojs | modules/ringo/engine.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/engine.js | Apache-2.0 |
exports.asJavaString = (object) => engine.asJavaString(object); | Get a wrapper for a string that exposes the java.lang.String methods to JavaScript
This is useful for accessing strings as java.lang.String without the cost of
creating a new instance.
@param {Object} object an object
@returns {Object} the object converted to a string and wrapped as native java object | exports.asJavaString | javascript | ringo/ringojs | modules/ringo/engine.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/engine.js | Apache-2.0 |
exports.getOptimizationLevel = () => engine.getOptimizationLevel(); | Get the Rhino optimization level for the current thread and context.
The optimization level is an integer between -1 (interpreter mode)
and 9 (compiled mode, all optimizations enabled). The default level
is 0.
@returns {Number} level an integer between -1 and 9 | exports.getOptimizationLevel | javascript | ringo/ringojs | modules/ringo/engine.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/engine.js | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.