0

I wish to extract the file path and then the filename with extension, essentially leaving me with the file name and file from an event object in AWS Lambda using Node.js

Here is an example file path

/home/mysite/public_html/services/wp-content/uploads/woocommerce_uploads/wcj_uploads/input_fields_uploads/myfilename.docx
var docfilename = event.line_items[0].meta_data[0].value.tmp_name;
var docextension = event.line_items[0].meta_data[0].value.tmp_name;

console.log(event.line_items[0].meta_data[0].value.tmp_name);

The desired output would just be "myfilename" in the first instance and "myfilename.docx" in the second instance

Gracie
  • 896
  • 5
  • 14
  • 34
  • Possible duplicate of [nodejs get file name from absolute path?](https://stackoverflow.com/questions/19811541/nodejs-get-file-name-from-absolute-path) – dmulter Feb 01 '19 at 16:17

3 Answers3

1

If I understand correctly, you can use Node.js internal path module:

'use strict';

const path = require('path');

const fullPath = '/home/mysite/public_html/services/wp-content/uploads/woocommerce_uploads/wcj_uploads/input_fields_uploads/myfilename.docx';

const extension = path.extname(fullPath);
const justFileName = path.basename(fullPath, extension);
const fileNameWithExtension = path.basename(fullPath);

console.log(justFileName);
console.log(fileNameWithExtension);
myfilename
myfilename.docx
vsemozhebuty
  • 12,992
  • 1
  • 26
  • 26
  • 1
    This looks great. There may be additional file extensions used in the future. Any way this could acommadate txt, rtf etc in the justFileName extension? – Gracie Feb 01 '19 at 12:52
  • 1
    You can use `path.extname` to determine the extension of the file, and then `path.basename` as answerer showed to get just the base filename if desired. – Elliot Nelson Feb 01 '19 at 12:54
  • Yes, I've updated the example. You can also look at https://nodejs.org/api/path.html for more details. – vsemozhebuty Feb 01 '19 at 12:58
0

You can split first by / and than take the last element split again by . and take the first element.

let filePath = `/home/mysite/public_html/services/wp-content/uploads/woocommerce_uploads/wcj_uploads/input_fields_uploads/myfilename.docx`

let splited = filePath.split('/').pop().split('.')[0]

console.log(splited)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
0

To achieve that I recommend using the split method like this:

var filePath = "/home/mysite/public_html/services/wp-content/uploads/woocommerce_uploads/wcj_uploads/input_fields_uploads/myfilename.docx";

let split1 = filePath.split("/"); // splits at the / character -> variable is an array containing all folders and the "myfilename.docx"

let split2 = split1[split1.length - 1]; // only takes the part after the last / -> variable is equal to "myfilename.docx"

let done = split2.split(".")[0]; // only takes the part before the . -> variable is equal to "myfilename"

console.log(done);
Sv443
  • 708
  • 1
  • 7
  • 27