rokojori-godot/_old-js/library.js

171 lines
2.7 KiB
JavaScript
Raw Normal View History

2024-04-27 15:03:50 +00:00
const { stat } = require("node:fs");
const fs = require( "node:fs/promises" );
async function getFiles( filePath )
{
return await fs.readdir( filePath );
}
2024-07-26 05:45:02 +00:00
async function isDirectory( filePath )
{
let stats = await fs.stat( filePath );
return stats.isDirectory();
}
2024-04-27 15:03:50 +00:00
async function exists( filePath )
{
try
{
let stats = await fs.stat( filePath );
let exists = stats !== undefined && stats !== null;
return Promise.resolve( exists );
}
catch( e )
{
}
return Promise.resolve( false );
}
async function loadUTF8( filePath )
{
try
{
let data = await fs.readFile( filePath );
let stringData = data.toString();
return Promise.resolve( stringData );
}
catch ( exception )
{
console.warn( exception );
}
return Promise.resolve( null );
}
async function saveUTF8( filePath, data )
{
try
{
await fs.writeFile( filePath, data );
return Promise.resolve( true );
}
catch ( exception )
{
console.warn( exception );
}
return Promise.resolve( false );
}
function makeSticky( regexp )
{
if ( regexp.sticky )
{
return regexp;
}
var source = regexp.source;
var flags = regexp.flags;
if ( flags.indexOf( "y" ) === -1 )
{
flags += "y";
}
return new RegExp( source, flags );
}
function makeGlobal( regexp )
{
if ( regexp.global )
{
return regexp;
}
var source = regexp.source;
var flags = regexp.flags;
if ( flags.indexOf( "g" ) === -1 )
{
flags += "g";
}
return new RegExp( source, flags );
}
function getMatches( source, regex )
{
regex = makeGlobal( regex );
let offset = 0;
let matches = [];
while ( offset < source.length )
{
regex.lastIndex = offset;
let result = regex.exec( source );
let match = result ? result[ 0 ] : null;
if ( result && result.index != offset && match.length > 0)
{
offset = result.index + match.length;
matches.push( { match:match, index: result.index } );
}
else
{
return matches;
}
}
return matches;
}
2024-04-27 15:03:50 +00:00
async function loadJSON( filePath )
{
let text = await loadUTF8( filePath );
if ( text === null )
{
return Promise.resolve( null );
}
try
{
let jsonObject = JSON.parse( text );
return Promise.resolve( jsonObject );
}
catch ( exception )
{
console.warn( exception );
}
return Promise.resolve( null );
}
function insertText( sourceText, insertText, insertPosition )
{
let before = sourceText.substring( 0, insertPosition );
let after = sourceText.substring( insertPosition, sourceText.length );
return before + insertText + after;
}
2024-04-27 15:03:50 +00:00
module.exports =
{
exists,
2024-07-26 05:45:02 +00:00
isDirectory,
2024-04-27 15:03:50 +00:00
loadUTF8,
saveUTF8,
loadJSON,
getFiles,
getMatches,
insertText
2024-04-27 15:03:50 +00:00
}