Is it possible to run an external command in Dart? I need to run the external command plutil, but everything I google gives me results to run Dart code from the command line, so I have not been able to find a solution. Thanks!
Example of Run external command in dart:
import 'dart:io';
void main(List<String> args) async {
var executable = 'ls';
if (Platform.isWindows) {
executable = 'dir';
}
final arguments = <String>[];
print('List Files and Directories');
print('============');
final process = await Process.start(executable, arguments, runInShell: true);
await stdout.addStream(process.stdout);
await stderr.addStream(process.stderr);
final exitCode = await process.exitCode;
print('============');
print('Exit code: $exitCode');
}
Related
I have this simple file:
class Console {
const Console();
void run() {
stdout
..writeln('Choose:\n')
..writeln(' 1) A')
..writeln(' 2) B\n')
final input = stdin.readLineSync() ?? '';
stdout.write('You have chosen $input');
}
}
How do I unit test this?
My best try is the following:
test('Making sure that invalid inputs return an error message', () async {
final process = await Process.start('dart', ['run', r'../bin/demo.dart']);
process.stdin.write('1');
process.stdout.transform(Utf8Decoder()).listen(print);
});
Since I have no idea on how to check for the stdout printed text, I am trying to at least display the strings
Choose:
1) A
2) B
using transform(Utf8Decoder()) but it's not working. Could you please point me towards the right direction?
Note: the main() function is located in lib/demo.dart so that's why I'm passing ../bin/demo.dart
i created a async/await function in another file thus its handler is returning a Future Object. Now i can't understand how to give response to client with content of that Future Object in Dart. I am using basic dart server with shelf package.Below is code where ht.handler('list') returns a Future Object and i want to send that string to client as response. But i am getting internal server error.
import 'dart:io';
import 'package:args/args.dart';
import 'package:shelf/shelf.dart' as shelf;
import 'package:shelf/shelf_io.dart' as io;
import 'HallTicket.dart' as ht;
// For Google Cloud Run, set _hostname to '0.0.0.0'.
const _hostname = 'localhost';
main(List<String> args) async {
var parser = ArgParser()..addOption('port', abbr: 'p');
var result = parser.parse(args);
// For Google Cloud Run, we respect the PORT environment variable
var portStr = result['port'] ?? Platform.environment['PORT'] ?? '8080';
var port = int.tryParse(portStr);
if (port == null) {
stdout.writeln('Could not parse port value "$portStr" into a number.');
// 64: command line usage error
exitCode = 64;
return;
}
var handler = const shelf.Pipeline()
.addMiddleware(shelf.logRequests())
.addHandler(_echoRequest);
var server = await io.serve(handler, _hostname, port);
print('Serving at http://${server.address.host}:${server.port}');
}
Future<shelf.Response> _echoRequest(shelf.Request request)async{
shelf.Response.ok('Request for "${request.url}"\n'+await ht.handler('list'));
}
The analyzer gives your the following warning for your _echoRequest method:
info: This function has a return type of 'Future', but
doesn't end with a return statement.
And if you check the requirement for addHandler you will see it expects a handler to be returned.
So you need to add the return which makes it work on my machine:
Future<shelf.Response> _echoRequest(shelf.Request request) async {
return shelf.Response.ok(
'Request for "${request.url}"\n' + await ht.handler('list2'),
headers: {'Content-Type': 'text/html'});
}
import 'dart:io';
import 'dart:async';
void main() {
HttpClient client = new HttpClient();
client.getUrl(Uri.parse('http://api.dartlang.org/docs/releases/latest/dart_io/HttpClientResponse.html'))
.then((HttpClientRequest request) => request.close())
.then((HttpClientResponse response) {
response.listen(print, onError: (e) {
print('error: $e');
});
});
}
The code above doesn't work, using similar method to listen like pipe and fold also throws an exception => Breaking on exception: The null object does not have a method 'cancel'.
Update
Here's the code example for when connect to local machine.
import 'dart:io';
import 'dart:async';
void main() {
HttpServer.bind('127.0.0.1', 8080)
.then((HttpServer server) {
server.listen((HttpRequest request) {
File f = new File('upload.html');
f.openRead().pipe(request.response);
});
HttpClient client = new HttpClient();
client.getUrl(Uri.parse('http://127.0.0.1:8080'))
.then((HttpClientRequest request) => request.close())
.then((HttpClientResponse response) {
response.listen(print, onError: (e) {
print('error: $e');
});
});
});
}
It prints out the bytes first and then throw an exception Breaking on exception: The null object does not have a method 'cancel'.
Dart Editor version 0.7.2_r27268. Dart SDK version 0.7.2.1_r27268. On Windows 64bit machine.
Your example works on my machine.
Please specify your Dart version and other system properties that could help debug the problem.
The code presented looks fine, and I have not been able to reproduce the error on either 0.7.2.1 nor bleeding edge. Do you know whether you network has any kind of proxy setup which could cause a direct HTTP connection to fail? You could try connecting to a server on your local machine instead. If it still fails I suggest opening a bug on https://code.google.com/p/dart/issues/list with detailed information.
Can we use dart to download a file?
For example in python
I'm using the HTTP package a lot. If you want to download a file that is not huge, you could use the HTTP package for a cleaner approach:
import 'package:http/http.dart' as http;
main() {
http.get(url).then((response) {
new File(path).writeAsBytes(response.bodyBytes);
});
}
What Alexandre wrote will perform better for larger files. Consider writing a helper function for that if you find the need for downloading files often.
Shailen's response is correct and can even be a little shorter with Stream.pipe.
import 'dart:io';
main() async {
final request = await HttpClient().getUrl(Uri.parse('http://example.com'));
final response = await request.close();
response.pipe(File('foo.txt').openWrite());
}
The python example linked to in the question involves requesting the contents of example.com and writing the response to a file.
Here is how you can do something similar in Dart:
import 'dart:io';
main() {
var url = Uri.parse('http://example.com');
var httpClient = new HttpClient();
httpClient.getUrl(url)
.then((HttpClientRequest request) {
return request.close();
})
.then((HttpClientResponse response) {
response.transform(new StringDecoder()).toList().then((data) {
var body = data.join('');
print(body);
var file = new File('foo.txt');
file.writeAsString(body).then((_) {
httpClient.close();
});
});
});
}
We can use http.readBytes(url).
await File(path).writeAsBytes(await http.readBytes('https://picsum.photos/200/300/?random'));
Yes, first of all you have to request to file url using http dart library like:
Response response = await get(Uri.parse(link));
after that your Response object (response) will get that file in self and you can simply write the response bytes to a file and that file will be your downloaded file.
as I open file like this:
File file = File('image.jpg')
then we have to send response bytes to this file like this:
file.writeAsBytes(response.bodyBytes);
now you have downloaded a image file successfully.. Congrates.
additional, for example let me show you a sample code to download a image file :
import 'dart:io';
import 'package:http/http.dart';
main(List<String> args) async {
var link =
"https://pps.whatsapp.net/v/t61.24694-
24/72779382_449683642563635_3243701117464346624_n.jpg?ccb=11-
4&oh=23e3bc2ce3f4940a70cb464494bbda76&oe=619B3B8C";
Response response = await get(Uri.parse(link));
File file = File('image.jpg');
file.writeAsBytes(response.bodyBytes);
}
look, this is the code and a file named image.jpg is downloaded at bottom in terminal view is our downloaded image.
screen shot
this is our actual image which we downloaded.
downloaded image
Could someone please show me an example of terminal input (question and response) in Dart (console) (latest r22223). The only example that I have seen doesn't appear to work or is incomplete.
Here's another option:
import "dart:async";
import "dart:io";
void main() {
stdout.write('> '); // stdout.write() rather than print() to avoid newline
new StringDecoder().bind(stdin).listen((str) { // Listen to a Stream<String>
print('"${str.trim()}"'); // Quote and parrot back the input
stdout.write('> '); // Prompt and keep listening
}, onDone: () => print('\nBye!')); // Stream is done, say bye
}
This appears to work fine on Linux and Windows. It quotes back to you whatever you enter at the prompt. You can exit by inputting EOF (control-D on Linux and other UNIX-like systems, control-Z followed by enter on Windows).
import "dart:async";
import "dart:io";
void main() {
print("Do you want to say something?");
Stream<String> input = stdin.transform(new StringDecoder());
StreamSubscription sub;
sub = input.listen((user_input) {
print("Really? \"${user_input.trim()}\"? That's all you have to say?");
sub.cancel();
});
}
Which example did you find, and how exactly was it wrong?