Html read properties file

File

The File interface provides information about files and allows JavaScript in a web page to access their content.

File objects are generally retrieved from a FileList object returned as a result of a user selecting files using the element, or from a drag and drop operation’s DataTransfer object.

A File object is a specific kind of Blob , and can be used in any context that a Blob can. In particular, FileReader , URL.createObjectURL() , createImageBitmap() , and XMLHttpRequest.send() accept both Blob s and File s.

See Using files from web applications for more information and examples.

Constructor

Instance properties

File.prototype.lastModified Read only Returns the last modified time of the file, in millisecond since the UNIX epoch (January 1st, 1970 at Midnight). File.prototype.lastModifiedDate Deprecated Read only Non-standard Returns the last modified Date of the file referenced by the File object. File.prototype.name Read only Returns the name of the file referenced by the File object. File.prototype.webkitRelativePath Read only Returns the path the URL of the File is relative to. File implements Blob , so it also has the following properties available to it: File.prototype.size Read only Returns the size of the file in bytes. File.prototype.type Read only Returns the MIME type of the file.

Читайте также:  Javascript and excel vba

Instance methods

The File interface doesn’t define any methods, but inherits methods from the Blob interface: Blob.prototype.slice([start[, end[, contentType]]]) Returns a new Blob object containing the data in the specified range of bytes of the source Blob . Blob.prototype.stream() Transforms the File into a ReadableStream that can be used to read the File contents. Blob.prototype.text() Transforms the File into a stream and reads it to completion. It returns a promise that resolves with a string (text). Blob.prototype.arrayBuffer() Transforms the File into a stream and reads it to completion. It returns a promise that resolves with an ArrayBuffer .

Specifications

Browser compatibility

See also

Found a content problem with this page?

Источник

How to read a properties file in javascript from project directory?

A properties file is a way of storing data in key-value pairs. In JavaScript, you may want to read this properties file from the project directory to use the data stored in it. This can be done by using the built-in File System (fs) module in Node.js. However, there are several methods to achieve this, each with its own benefits and drawbacks. This guide will introduce the different methods to read a properties file in JavaScript from the project directory, as well as their pros and cons.

Method 1: Using fs.readFileSync()

Reading Properties File in JavaScript using fs.readFileSync()

Here are the steps to read a properties file in JavaScript using fs.readFileSync():

  1. Define the path to your properties file. For example, if your properties file is named «config.properties» and is located in the project directory, the path would be:
const path = './config.properties';
  1. Use the fs.readFileSync() method to read the contents of the properties file. This method takes two arguments: the path to the file and the encoding format. In this case, we will use ‘utf-8’ as the encoding format.
const properties = fs.readFileSync(path, 'utf-8');
  1. Parse the properties file contents into an object. You can use the following code to achieve this:
const propertiesObject = >; properties.split('\n').forEach(function(line)  if (line.length === 0 || line.charAt(0) === '#')  return; > const keyValue = line.split('='); const key = keyValue[0].trim(); const value = keyValue[1].trim(); propertiesObject[key] = value; >);

This code will split the properties file contents by line, ignore any comment lines (starting with ‘#’), split each line by the ‘=’ character, and add each key-value pair to the propertiesObject.

const serverUrl = propertiesObject['server.url']; const username = propertiesObject['username']; const password = propertiesObject['password'];

This code will retrieve the values of the ‘server.url’, ‘username’, and ‘password’ properties from the propertiesObject.

Here is the complete code:

const fs = require('fs'); const path = './config.properties'; const properties = fs.readFileSync(path, 'utf-8'); const propertiesObject = >; properties.split('\n').forEach(function(line)  if (line.length === 0 || line.charAt(0) === '#')  return; > const keyValue = line.split('='); const key = keyValue[0].trim(); const value = keyValue[1].trim(); propertiesObject[key] = value; >); const serverUrl = propertiesObject['server.url']; const username = propertiesObject['username']; const password = propertiesObject['password'];

I hope this helps you read a properties file in JavaScript using fs.readFileSync().

Method 2: Using fs.readFile()

To read a properties file in JavaScript from the project directory, you can use the fs module in Node.js. Here’s an example code using fs.readFile() :

const fs = require('fs'); fs.readFile('./config.properties', 'utf8', function(err, data)  if (err) throw err; console.log(data); >);

This code reads the config.properties file from the project directory and logs its contents to the console. Let’s break down the code:

  1. First, we import the fs module using require() .
  2. We call the readFile() method on the fs module, passing in the path to the file we want to read ( ‘./config.properties’ ) and the encoding ( ‘utf8’ ).
  3. The readFile() method takes a callback function as its second argument. This function is called once the file has been read, and it receives two arguments: an error object (if an error occurred) and the contents of the file.
  4. In our callback function, we check if an error occurred ( if (err) throw err; ) and then log the contents of the file to the console using console.log(data) .

That’s it! This code should allow you to read a properties file in JavaScript from the project directory using fs.readFile() .

Method 3: Using fs.readdir() and fs.readFile()

Here are the steps to read a properties file in JavaScript from the project directory using fs.readdir() and fs.readFile() :

fs.readdir('.', (err, files) =>  if (err) throw err; console.log(files); >);

This will log an array of filenames in the project directory to the console.

const propertiesFiles = files.filter(file => file.endsWith('.properties'));

This will create a new array containing only the filenames that end with .properties .

propertiesFiles.forEach(file =>  fs.readFile(file, 'utf8', (err, data) =>  if (err) throw err; console.log(data); >); >);

This will log the contents of each properties file to the console.

const fs = require('fs'); fs.readdir('.', (err, files) =>  if (err) throw err; const propertiesFiles = files.filter(file => file.endsWith('.properties')); propertiesFiles.forEach(file =>  fs.readFile(file, 'utf8', (err, data) =>  if (err) throw err; console.log(data); >); >); >);

This code will read all the properties files in the project directory and log their contents to the console.

Method 4: Using a Third-Party Package

To read a properties file in JavaScript from the project directory using a third-party package, you can use the properties-reader package. Here are the steps to implement it:

npm install properties-reader
const PropertiesReader = require('properties-reader');
const properties = PropertiesReader('path/to/properties/file.properties');
const value = properties.get('property_name');

Here is an example code snippet that implements the above steps:

const PropertiesReader = require('properties-reader'); const properties = PropertiesReader('path/to/properties/file.properties'); const value = properties.get('property_name'); console.log(value);

In the above code, replace path/to/properties/file.properties with the actual path to your properties file, and property_name with the name of the property you want to access.

That’s it! This is how you can read a properties file in JavaScript from the project directory using the properties-reader package.

Источник

How to Read a Local File Using Javascript in Browser (.txt .json etc)

Local files can be opened and read in the browser using the Javascript FileReader object.

Quick Sample Code

   

Demo — Reading a Local Text File

This example reads a text file from the local disk :

How is File Reading Done ?

This tutorial will show how to read a file from the local filesystem by implementing the following steps :

  • Allowing the user to choose file from the device through file element.
  • Reading metadata (name, type & size) of the file using properties of the selected File object.
  • Reading contents of the file using FileReader object.

Step 1 — Allow User to Choose the File

Step 2 — Read File Metadata (Name, Type & Size) using Properties of File Object

The file selected by the user can be accessed as a File object in Javascript. The name, type & size properties of this File object gives the metadata of the chosen file.

document.querySelector("#read-button").addEventListener('click', function() < if(document.querySelector("#file-input").files.length == 0) < alert('Error : No file selected'); return; >// file selected by user let file = document.querySelector("#file-input").files[0]; // file name let file_name = file.name; // file MIME type let file_type = file.type; // file size in bytes let file_size = file.size; >); 

Step 3 — Read File Contents using FileReader Object

The contents of the selected File object is read using the FileReader object. Reading is performed asynchronously, and both text and binary file formats can be read.

  • Text files (TXT, CSV, JSON, HTML etc) can be read using the readAsText() method.
  • Binary files (EXE, PNG, MP4 etc) can be read using the readAsArrayBuffer() method.
  • Data url string can be read using the readAsDataURL() method.
document.querySelector("#read-button").addEventListener('click', function() < if(document.querySelector("#file-input").files.length == 0) < alert('Error : No file selected'); return; >// file selected by user let file = document.querySelector("#file-input").files[0]; // new FileReader object let reader = new FileReader(); // event fired when file reading finished reader.addEventListener('load', function(e) < // contents of the file let text = e.target.result; document.querySelector("#file-contents").textContent = text; >); // event fired when file reading failed reader.addEventListener('error', function() < alert('Error : Failed to read file'); >); // read file as text file reader.readAsText(file); >); 

Other FAQs on Reading a File with Javascript

The progress event of the FileReader object handles reading progress of the file.

// file read progress event reader.addEventListener('progress', function(e) < if(e.lengthComputable == true) < // percentage of the file read let percent_read = Math.floor((e.loaded/e.total)*100); console.log(percent_read + '% read'); >>); 

To get the binary data of file, the readAsBinaryString() / readAsArrayBuffer method needs to be used.

A file on a server can be read with Javascript by downloading the file with AJAX and parsing the server response.

Источник

Оцените статью