Read a file
Node JS
Buffering Contents with fs.readFile
[js]
// synchronously
var fs = require(‘fs’);
try {
var data = fs.readFileSync(‘my-file.txt’, ‘utf8’);
console.log(data);
} catch(e) {
console.log(‘Error:’, e.stack);
}
[/js]
[js]
//Unsync
var fs = require(‘fs’);
fs.readFile(‘my-file.txt’, ‘utf8’, function(err, data) {
if (err) throw err;
console.log(data);
});
[/js]
Streaming Contents
[js]
var fs = require(‘fs’);
var data = ”;
var readStream = fs.createReadStream(‘my-file.txt’, ‘utf8’);
readStream.on(‘data’, function(chunk) {
data += chunk;
}).on(‘end’, function() {
console.log(data);
});
[/js]
Others
Read line by line an upload file, write to a temporary file, delete upload file and rename the temporary file
- C#
[c]using (StreamReader reader = new StreamReader(upLoadFilePath))
{
using (StreamWriter writer = new StreamWriter(tempfile))
{
string line = reader.ReadLine();
while (!reader.EndOfStream)
{
writer.WriteLine(line);
line = reader.ReadLine();
}
}
}[/c][c] System.IO.File.Delete(upLoadFilePath);
System.IO.File.Move(tempfile, upLoadFilePath);[/c]
Read a file, delete last character
- C#
[c] string myFileData;
myFileData = System.IO.File.ReadAllText(upLoadFilePath);
<pre>if (myFileData.EndsWith(" " + Environment.NewLine))
{
char[] charsToTrim = {‘\r’, ‘\n’, ‘ ‘};
System.IO.File.WriteAllText(tempfile, myFileData.TrimEnd(charsToTrim));
}[/c]
Read line by line an upload file, delete 2 first lines
- C#
[c]
String line = null;
int line_number = 0;
int lines_to_delete = 1;
using (StreamReader reader = new StreamReader(upLoadFilePath))
{
using (StreamWriter writer = new StreamWriter(tempfile))
{
while ((line = reader.ReadLine()) != null)
{
// Remove first 2 header rows
line_number++;
if (line_number > lines_to_delete)
break;
}while ((line = reader.ReadLine()) != null)
{
// Remove last character "|" of row
if (line.Substring(line.Length – 1) == "|")
{
line = line.Remove(line.Length – 1);
}
writer.WriteLine(line);
}
}
}if (System.IO.File.Exists(tempfile))
{
System.IO.File.Delete(upLoadFilePath);
System.IO.File.Move(tempfile, upLoadFilePath);
}[/c]
Leave a Reply