Get directory of a file name in Javascript
I don't know if there is any built in functionality for this, but it's pretty straight forward to get the path.
path = path.substring(0,path.lastIndexOf("\\")+1);
Way to get file name and parent directory name
You can .split('/')
the URL on the forward slash character /
. Then .slice(-2)
to get the last 2 items from the split items. Then .join('/')
those two items back together with a slash.
function parentPath(url) { return url.split('/').slice(-2).join('/')}
console.log(parentPath('/directory1/index.html?v=1.1')) console.log(parentPath('directory1/directory2/dircetory3/index.html?v=1.1')) console.log(parentPath('/index.html?v=1.1'))console.log(parentPath('index.html?v=1.1'))
Javascript - How to extract filename from a file input control
Assuming your <input type="file" > has an id of upload this should hopefully do the trick:
var fullPath = document.getElementById('upload').value;
if (fullPath) {
var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
var filename = fullPath.substring(startIndex);
if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
filename = filename.substring(1);
}
alert(filename);
}
Get directory from a file path or url
Using path module of node.js:
path.dirname('/this/is/a/path/to/a/file');
returns
'/this/is/a/path/to/a'
Get File Name and Parent Folder of URL
Using .split()
, you can select the last 2 elements and join them together after:
var url = "www.example.com/get/thisfolder/thanks.html";var path = url.split('/').slice(-2).join('/'); alert(path);
Read files from directory and save to array of object
I got it working after reading several articles on closure and promises. The below code works for me and sends me array of employees that are processed.
const directoryPath = './tax/';
function readFiles(dirname) {
fs.readdir(dirname, async function (err,filenames) {
if(err) {
return err;
}
let promiseArr = filenames.map( file=> {
return new Promise((resolve)=>{
processFile(file, resolve)
})
});
Promise.all(promiseArr).then((ret)=>console.log(ret));
})
}
function processFile(file, callback) {
const filePath = path.join(__dirname,directoryPath,file);
const readStream = fs.createReadStream(filePath);
const fileContent = readline.createInterface({
input: readStream
});
let employeeObj = {
empId : '',
TotalEarning:'',
ProfessionalTax:0,
GrossIncome:0,
isDone:false
};
fileContent.on('line', function(line) {
if(!employeeObj.empId && line.includes("Employee:")) {
const empId = line.replace('Employee: ','').split(" ")[0];
employeeObj.empId = empId;
}
else if(line.includes('Total Earnings')) {
const amount = line.replace(/[^0-9.]/g,'');
employeeObj.TotalEarning = amount;
}
else if(line.includes('Profession Tax')) {
const amount = line.split(" ").pop() || 0;
employeeObj.ProfessionalTax = amount;
}
else if(line.includes('Gross Income')) {
const amount = line.replace(/[^0-9.]/g,'');
employeeObj.GrossIncome = amount ||0;
}
else if(line.includes('finance department immediately')) {
employeeObj.isDone = true;
return callback(employeeObj);
}
});
fileContent.on('close', function() {
fileContent.close();
});
}
readFiles(directoryPath);
Surely, the code can be improved further.
Related Topics
Javascript Function Not Defined Error (But It Is Defined)
Check If a Number Has a Decimal Place/Is a Whole Number
Call a Function from an If-Statement Inside a Function
How to Get Full Path of Selected File on Change of <Input Type='File'> Using Javascript, Jquery-Ajax
How to Bind on Click Event on Dynamically Created Button in Angular 6
How to Submit an HTML Form Without Redirection
Creating a Leaderboard in Html/Js
How to Output Date in JavaScript in Iso 8601 Without Milliseconds and With Z
Why Does This Onclick Event Not Work in an HTML Iframe
How to Prevent User to Enter Specific Key Using JavaScript
Regex to Replace Everything Except Numbers and a Decimal Point
Filtering Multiple Items With Es6 Array Functions
Why Does Google Chrome Always Add Space After Selected Text
How to Hide Select Options With Javascript (Cross Browser)
How to Remove All Null and Empty String Values from an Object
Scroll to Element from Typescript Code (Angular 5)
Get the Contents of a Table Row With a Button Click
How to Add a New Object (Key-Value Pair) to an Array in JavaScript