Check that file exists: Difference between revisions

→‎{{header|JavaScript}}: Added file system functions for MacOS Javascript for Automation (JXA)
m (→‎{{header|Haskell}}: Specified imports, applied hlint, hindent)
(→‎{{header|JavaScript}}: Added file system functions for MacOS Javascript for Automation (JXA))
Line 1,124:
 
=={{header|JavaScript}}==
Javascript interpreters are now widely embedded in contexts which do have access to file systems, but the early context of browser scripting has precluded the inclusion of file system libraries in the definition of the language itself.
{{works with|JScript}}
Each non-browser JS context is likely to have its own home-grown and unstandardised fileSystem library.
===JScript===
<lang javascript>var fso = new ActiveXObject("Scripting.FileSystemObject");
 
Line 1,131 ⟶ 1,133:
fso.FolderExists('docs');
fso.FolderExists('c:/docs');</lang>
 
===macOS JavaScript for Automation===
<lang JavaScript>(() => {
 
// SYSTEM DIRECTORY FUNCTIONS
// FOR MAC OS JAVASCRIPT FOR AUTOMATION SCRIPTING -------------------------
 
// doesDirectoryExist :: String -> IO Bool
const doesDirectoryExist = strPath => {
const
dm = $.NSFileManager.defaultManager,
ref = Ref();
return dm
.fileExistsAtPathIsDirectory(
$(strPath)
.stringByStandardizingPath, ref
) && ref[0] === 1;
};
 
// doesFileExist :: String -> Bool
const doesFileExist = strPath => {
var error = $();
return (
$.NSFileManager.defaultManager
.attributesOfItemAtPathError(
$(strPath)
.stringByStandardizingPath,
error
),
error.code === undefined
);
};
 
// getCurrentDirectory :: String
const getCurrentDirectory = () =>
ObjC.unwrap($.NSFileManager.defaultManager.currentDirectoryPath);
 
// getFinderDirectory :: String
const getFinderDirectory = () =>
Application('Finder')
.insertionLocation()
.url()
.slice(7);
 
// getHomeDirectory :: String
const getHomeDirectory = () =>
ObjC.unwrap($.NSHomeDirectory());
 
// setCurrentDirectory :: String -> IO ()
const setCurrentDirectory = strPath =>
$.NSFileManager.defaultManager
.changeCurrentDirectoryPath(
$(strPath)
.stringByStandardizingPath
);
 
// GENERIC FUNCTIONS FOR THE TEST -----------------------------------------
 
// A list of functions applied to a list of arguments
// <*> :: [(a -> b)] -> [a] -> [b]
const ap = (fs, xs) => //
[].concat.apply([], fs.map(f => //
[].concat.apply([], xs.map(x => [f(x)]))));
 
// show :: a -> String
const show = x => JSON.stringify(x, null, 2);
 
// TEST -------------------------------------------------------------------
return (
setCurrentDirectory('~/Desktop'),
show(ap(
[doesFileExist, doesDirectoryExist],
['input.txt', '/input.txt', 'docs', '/docs']
))
);
})();</lang>
{{Out}}
The first four booleans are returned by doesFileExist – the last four by
doesDirectoryExist, which returns false in the case of files which do
do exist but are not directories.
<pre>[
true,
true,
true,
true,
false,
false,
true,
true
]</pre>
 
=={{header|Julia}}==
9,659

edits