Ci dessous un exemple complet:
La lecture se fait de manière asynchrone par l'ouverture d'un stream en lecture. L'avantage de se mode de fonctionnement est qu'il permet de traiter des gros fichiers, seul un tronçon de fichier transite en mémoire.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Le source en coffeescript | |
(algorithme c.antunes) | |
fs = require('fs') | |
readlines = (input , func) -> | |
remaining = '' | |
input.on 'data' , (data) -> | |
str = data.toString('ascii') | |
remaining += str | |
index = remaining.indexOf('\n') | |
while (index > -1 ) | |
line = remaining.substring(0 , index ) | |
remaining = remaining.substring(index + 1 ) | |
func line | |
index = remaining.indexOf('\n') | |
input.on 'end' , -> | |
if remaining.length > 0 | |
func remaining | |
input = fs.createReadStream('essai.txt') | |
readlines input , (msg) -> console.log (msg) | |
############# | |
Le fichier en entrée | |
############ | |
Eric | |
German | |
vous donne | |
rendez-vous le | |
19/06/12 aux solutions linux 2012 | |
Le blues des frameworks MVC | |
############## | |
Son exécution | |
############# | |
coffee -c lignealigne.coffee | |
german@german-1001PX:~$ node lignealigne.js | |
Eric | |
German | |
vous donne | |
rendez-vous le | |
19/06/12 aux solutions linux 2012 | |
Le blues des frameworks MVC | |
La traduction en javascript donne:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
var fs, input, readlines; | |
fs = require('fs'); | |
readlines = function(input, func) { | |
var remaining; | |
remaining = ''; | |
input.on('data', function(data) { | |
var index, line, str, _results; | |
str = data.toString('ascii'); | |
remaining += str; | |
index = remaining.indexOf('\n'); | |
_results = []; | |
while (index > -1) { | |
line = remaining.substring(0, index); | |
remaining = remaining.substring(index + 1); | |
func(line); | |
_results.push(index = remaining.indexOf('\n')); | |
} | |
return _results; | |
}); | |
return input.on('end', function() { | |
if (remaining.length > 0) { | |
return func(remaining); | |
} | |
}); | |
}; | |
input = fs.createReadStream('essai.txt'); | |
readlines(input, function(msg) { | |
return console.log(msg); | |
}); | |
}).call(this); |
Aucun commentaire:
Enregistrer un commentaire