I'm new to this dart stuff and having problems with creating a list directory.tell me how to handle the exception so that the loop continues
void main() async{
Directory baseDir=new Directory('l:\\');
print(baseDir.path);
try {
await for (var entity in baseDir.list(recursive: true, followLinks: false)){
print(entity);
}
}
catch(e) {
print("Error: $e");
}
}
Error: FileSystemException: Directory listing failed, path = 'l:$RECYCLE.BIN\S-1-5-18*' (OS Error: access denied.
, errno = 5)
catch(e) {
print("Error: $e");
continue;
}
does not work because it is not in the loop body
You should be able to use Stream.handleError to swallow FileSystemExceptions:
import 'dart:io';
void main() async {
var baseDir = Directory.current;
var stream = baseDir
.list(
recursive: true,
followLinks: false,
)
.handleError(
(e) => print('Ignoring error: $e'),
test: (e) => e is FileSystemException,
);
await for (var entity in stream) {
print(entity);
}
print('Completed successfully.');
}
I don't have a Windows machine handy with a Dart development environment, but trying to simulate an equivalent situation as yours on my Linux machine:
$ mkdir someSubdir
$ chmod ugo-rx someSubdir # Remove permissions to list or enter the directory.
$ dart dirlist.dart
Directory: '/tmp/dirlist/someSubdir'
Ignoring error: FileSystemException: Directory listing failed, path = '/tmp/dirlist/someSubdir' (OS Error: Permission denied, errno = 13)
File: '/tmp/dirlist/dirlist.dart'
Completed successfully.
Also see: https://dart.dev/tutorials/language/streams#modify-stream-methods
Related
I am reading a file present on a network drive using dart. I want to return a blank list in case the file does not exist or the network cannot be accessed.
I have tried using try/catch and try/on blocks but I don't seem to be able to handle the exception.
Code
readJSONReport(String filePath) async {
/// If file exists on shared network folder,
/// read it and return the list. Else return blank list
List<dynamic> jsonList = [];
try {
File file = await File(filePath);
if (file.existsSync()) {
jsonList = json.decode(await file.readAsString());
}
} on FileSystemException {
print("File not found");
}
return jsonList;
}
Error Message
Unhandled exception:
FileSystemException: Cannot open file, path = '\\10.0.169.142\Users\Public\shared\reports\merged_report.json' (OS Error: The network path was not found.
, errno = 53)
#0 _File.open.<anonymous closure> (dart:io/file_impl.dart:356:9)
<asynchronous suspension>
Another way to ask the same thing would be:
How to check if a file exists on a network path using dart?
OP Here. Turns out, the exception was being raised from a different part of the code. Adding the code I use now to read a JSON file while checking whether the file exists or not.
import 'dart:io';
readJSONReport(String filePath) async {
/// read report file generated by JSON Reporter
/// if file exists, read it and return the list
/// if file does not exist, return empty list
List<dynamic> jsonList = [];
try {
File file = await File(filePath);
print("Reading $filePath");
if (await file.exists()) {
jsonList = json.decode(await file.readAsString());
} else {
print("File does not exist");
}
} catch (e, stacktrace) {
print("Exception occured: $e stackTrace: $stacktrace");
}
return jsonList;
}
Please note that the JSON I am reading starts as a list (as you can expect from a cucumber-json report).
I'm trying to use the rollup JS API. rollup.rollup doesn't require me to specify the output option but it appears rollup.watch does for some reason.
Here's what I've got:
#!/usr/bin/env node
import * as rollup from 'rollup';
async function main() {
const watcher = rollup.watch({
input: 'src/main.ts',
// output: {
// dir: 'dist'
// }
})
watcher.on('event', event => {
console.log(event);
})
}
main().catch(err => {
console.error(err);
process.exit(1);
})
It's saying:
{
code: 'ERROR',
error: Error: You must specify "output.file" or "output.dir" for the build.
at error (file:///somepath/screeps/node_modules/rollup/dist/es/shared/rollup.js:10380:30
)
at Object.write (file:///somepath/screeps/node_modules/rollup/dist/es/shared/rollup.js:1
8594:24)
at file:///somepath/screeps/node_modules/rollup/dist/es/shared/watch.js:7083:86
at Array.map (<anonymous>)
at Task.run (file:///somepath/screeps/node_modules/rollup/dist/es/shared/watch.js:7083:6
3)
at async Watcher.run (file:///somepath/screeps/node_modules/rollup/dist/es/shared/watch.
js:7003:17) {
code: 'MISSING_OPTION'
}
}
I should be able to get what I need out of the event emitter though -- I don't want to write it to disk. How do I disable that?
Turns out there's a watch.skipWrite option.
My main goal is to download a file from a link and then save it to the phone's internal storage so that it'll be accessible through the phone's file manager. I'm currently trying out Dio package by running the example code given in the package's repo. Upon running the program, I ran into a path problem. When I used ./example/flutter.png as the download path, I/flutter (10109): FileSystemException: Cannot open file, path = './example/flutter.png' (OS Error: No such file or directory, errno = 2) shows up. And when I used (await getApplicationDocumentsDirectory()).path which produces a String with the value of: /data/user/0/com.example.downloadexample/app_flutter as the path, no error showed up, but the file wasn't there. I tried different variation of the latter path, but with no success. Can someone help me with this problem?
Many thanks in advance.
I use http package, not the Dio, the code:
Future<String> fetchNetFileToDoc(String url, String filename) async {
final path = await getApplicationDocumentsDirectory();
File docFile = File('$path/$filename');
if(await docFile.exists()){
print( '${docFile.path} exits');
return docFile.path;
}
http.Response response = await http.get(url);
// todo - check status
await docFile.writeAsBytes(response.bodyBytes, flush: true);
return docFile.path;
}
if I invoke this method, like: fetchNetFileToDoc('http://a.com/a.mp3', 'a.mp3')
it shows the same error:
FileSystemException: Cannot open file, path= 'Direcotry: '/data/user/0/com.example.master_lu/app_flutter'/a.mp3' (OS Error: No such file or directory, errno = 2)
But if I use getTemporaryDirectory(), change code to this:
Future<String> fetchNetFileToTemp(String url, String filename) async {
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;
File tempFile = File('$tempPath/$filename');
if(await tempFile.exists()){
print( '${tempFile.path} exits');
return tempFile.path;
}
http.Response response = await http.get(url);
// todo - check status
await tempFile.writeAsBytes(response.bodyBytes, flush: true);
return tempFile.path;
}
That's ok, it works with the internal storage. Save the file into the data/user/0/com.example.master_lu/cache/a.mp3
The master_lu is the name of my project.
The latest=> I sovle my problem, await getApplicationDocumentsDirectory return Future<Directory>
so, here is the right code:
Future<String> fetchNetFileToDoc(String url, String filename) async {
final docDir = await getApplicationDocumentsDirectory();
String docPath = docDir.path;
File docFile = File('$docPath/$filename');
if(await docFile.exists()){
print( '${docFile.path} exits');
return docFile.path;
}
http.Response response = await http.get(url);
// todo - check status
await docFile.writeAsBytes(response.bodyBytes, flush: true);
return docFile.path;
}
The dart cookbook recipe 'Renaming a file, directory, or symlink' at https://www.dartlang.org/dart-vm/dart-by-example#renaming-a-file-directory-or-symlink doesn't seem to work as expected:
import 'dart:io';
main() async {
// Get the system temp directory.
var systemTempDir = Directory.systemTemp;
// Create a file.
var file = await new File('${systemTempDir.path}\\foo.txt').create();
// Prints path ending with `foo.txt`.
print('The path is ${file.path}');
// Rename the file.
await file.rename('${systemTempDir.path}\\bar.txt');
// Prints path ending with `bar.txt`.
print('The path is ${file.path}');
}
The output shows that the internal path field of the file object has not been changed (although the rename is successful):
[Running] dart "d:\src\dart\renameAsOnWeb.dart"
The path is C:\Users\guivh\AppData\Local\Temp\foo.txt
The path is C:\Users\guivh\AppData\Local\Temp\foo.txt
[Done] exited with code=0 in 0.327 seconds
I have extended / reworked the cookbook example to further investigate this:
import 'dart:io';
main() async {
var systemTempDir = Directory.systemTemp;
var file = await new File('${systemTempDir.path}\\foo.txt').create();
print('The file is located at ${file.path}');
File toDelete;
var newName = '${systemTempDir.path}\\fubar.toodeloo';
await file.rename(newName);
if (await new File(newName).exists() == false) {
print('The rename failed: there is no ${newName} file');
} else {
var newFile = new File(newName);
print('The rename was succesful');
var nameChangedInObject = file.path == newName;
if (nameChangedInObject) {
print('The path of the file object has changed correctly');
toDelete = newFile;
} else {
print(
'The path in the file object still is: ${file.path}');
toDelete = newFile;
}
await toDelete.delete();
print(
'And now, ${toDelete.path} is gone: ${await toDelete.exists() == false}');
}
}
And this output confirms the fact that the internal path field is not updated with the new name:
[Running] dart "d:\src\dart\renamingExample.dart"
The file is located at C:\Users\guivh\AppData\Local\Temp\foo.txt
The rename was succesful
The path in the file object still is: C:\Users\guivh\AppData\Local\Temp\foo.txt
And now, C:\Users\guivh\AppData\Local\Temp\fubar.toodeloo is gone: true
[Done] exited with code=0 in 0.369 seconds
I am runing the dev version on a windows box:
PS D:\src\dart> dart --version
Dart VM version: 2.0.0-dev.39.0 (Fri Mar 16 00:17:07 2018 +0100) on "windows_x64"
PS D:\src\dart>
Can somebody please explain what is going on here?
The example is wrong. The File object is immutable, so it definitely won't be changed by the rename operation. The example is wrong in expecting so.
I want to call a polymer webapp directly via command line or via 'Process' in a dart file.
I know when running it via the dart editor, a server on port 8080 is created and listening to requests for the /web folder.
but when launching
dartium/chrome.exe path/To/Index.html
from console its simply loading the files inside the browser but wont start a server for the client.
via
file:://path/to/file.html [no 'dart is not runnning' warning, but no polymer content]
or
127.x.x.x.x.x.x.x.x:xxxxxxxx/app/index.html will obviously tell me
'This webpage is not available'
DartEditor lauches pub serve. You can do this manually without Darteditor (since Dart 1.5 AFAIK). Just launch
pub serve
from within your Polymer app package directory.
Inside your console app launch the browser with the URL that loads the page from this server.
You could also include web server functionality into your console application that serves the Polymer app to your browser.
pub help serve
lists the available options.
You can try this script as an example how to call a polymer webapp directly via 'Process' in a dart file.
This example also includes launch of default browser.
import "dart:async";
import "dart:io";
import "package:path/path.dart" as pathos;
void main(List<String> args) {
String app;
String file;
switch (args.length) {
case 1:
app = args[0];
break;
case 2:
app = args[0];
file = args[1];
break;
default:
print("Usage: pubserve.dart app_path [file_name]");
exit(0);
}
if(!new Directory(app).existsSync()) {
print("Directory not exists: $app");
exit(-1);
}
pubServe(app, file).then((exitCode) {
exit(exitCode);
});
}
Future<int> pubServe(String app, String file) {
var sdk = Platform.environment["DART_SDK"];
if (sdk == null) {
print("Dart SDK not found");
return new Future(() => -1);
}
var executable = pathos.join(sdk, "bin", "pub");
var pattern = r"^Serving (?:.*) web on (.*)$";
var regexp = new RegExp(pattern);
return Process.start(executable, ["serve"], runInShell: true,
workingDirectory: app).then((process) {
process.stdout.listen((data) {
var string = new String.fromCharCodes(data);
for (var c in data) {
stdout.writeCharCode(c);
}
var match = regexp.matchAsPrefix(string);
if (match != null) {
var url = match.group(1);
if (file != null) {
url += "/$file";
}
Timer.run(() => runBrowser(url));
}
});
process.stderr.pipe(stderr);
stdin.pipe(process.stdin);
return process.exitCode.then((exitCode) {
return exitCode;
});
});
}
void runBrowser(String url) {
var fail = false;
switch (Platform.operatingSystem) {
case "linux":
Process.run("x-www-browser", [url]);
break;
case "macos":
Process.run("open", [url]);
break;
case "windows":
Process.run("explorer", [url]);
break;
default:
fail = true;
break;
}
if (!fail) {
//print("Start browsing...");
}
}
P.S.
NOTE:
If you run this script from Dart Editor, Editor will never stops execution of subprocess (pub serve in our case) when you stop current script in Dart Editor.
This is not related only to this script. Editor always keep subprocesses alive.
If you run it from cmd-line it terminates pub serve correctly.