how to read a file in js code example

Example 1: read file javascript

// As with JSON, use the Fetch API & ES6
fetch('something.txt')
  .then(response => response.text())
  .then(data => {
  	// Do something with your data
  	console.log(data);
  });

Example 2: how to load localt ext file in js

const fileUrl = '' // provide file location

fetch(fileUrl)
   .then( r => r.text() )
   .then( t => console.log(t) )

Example 3: how to read a file in javascript

fetch('file.txt')
  .then(response => response.text())
  .then(text => console.log(text))
  // outputs the content of the text file

Example 4: js read a ini file

/* 

Read a ini file

[Section1]
Param1=value1
[Section2]
Param2=value2

*/
var fs = require("fs");

function parseINIString(data){
    var regex = {
        section: /^\s*\[\s*([^\]]*)\s*\]\s*$/,
        param: /^\s*([^=]+?)\s*=\s*(.*?)\s*$/,
        comment: /^\s*;.*$/
    };
    var value = {};
    var lines = data.split(/[\r\n]+/);
    var section = null;
    lines.forEach(function(line){
        if(regex.comment.test(line)){
            return;
        }else if(regex.param.test(line)){
            var match = line.match(regex.param);
            if(section){
                value[section][match[1]] = match[2];
            }else{
                value[match[1]] = match[2];
            }
        }else if(regex.section.test(line)){
            var match = line.match(regex.section);
            value[match[1]] = {};
            section = match[1];
        }else if(line.length == 0 && section){
            section = null;
        };
    });
    return value;
}

try {
    var data = fs.readFileSync('C:\\data\\data.dat', 'utf8');

    var javascript_ini = parseINIString(data);
    console.log(javascript_ini['Section1']);

} 
catch(e) {
    console.log(e);
}

Example 5: Read files in JavaScript

function readImage(file) {  //function readImage(file) {
  // Check if the file is an image.
  if (file.type && !file.type.startsWith('image/')) {
    console.log('File is not an image.', file.type, file);
    return;
  }

  const reader = new FileReader();
  reader.addEventListener('load', (event) => {
    img.src = event.target.result;
  });
  reader.readAsDataURL(file);
} Check if the file is an image.  if (file.type && !file.type.startsWith('image/')) {    console.log('File is not an image.', file.type, file);    return;  }  const reader = new FileReader();  reader.addEventListener('load', (event) => {    img.src = event.target.result;  });  reader.readAsDataURL(file);}