Get full file path in Node.js
Javascriptnode.jsJavascript Problem Overview
I have an application which uploads csv file into a particular folder, say, "uploads".
Now I want to get the full path of that csv file, for example, D:\MyNodeApp\uploads\Test.csv
.
How do I get the file location in Node.js? I used multer to upload file.
Javascript Solutions
Solution 1 - Javascript
var path = require("path");
var absolutePath = path.resolve("Relative file path");
You dir structure for example:
C:->WebServer->Public->Uploads->MyFile.csv
and your working directory would be Public for example, path.resolve would be like that.
path.resolve("./Uploads/MyFile.csv");
POSIX home/WebServer/Public/Uploads/MyFile.csv
WINDOWS C:\WebServer\Public\Uploads\MyFile.csv
this solution is multiplatform and allows your application to work on both windows and posix machines.
Solution 2 - Javascript
Get all files from folder and print each file description.
const path = require( "path" );
const fs = require( 'fs' );
const log = console.log;
const folder = './';
fs.readdirSync( folder ).forEach( file => {
const extname = path.extname( file );
const filename = path.basename( file, extname );
const absolutePath = path.resolve( folder, file );
log( "File : ", file );
log( "filename : ", filename );
log( "extname : ", extname );
log( "absolutePath : ", absolutePath);
});
Solution 3 - Javascript
Assuming you are using multer with express, try this in your controller method:
var path = require('path');
//gets your app's root path
var root = path.dirname(require.main.filename)
// joins uploaded file path with root. replace filename with your input field name
var absolutePath = path.join(root,req.files['filename'].path)
Solution 4 - Javascript
In TypeScript, I did the following based on the relative file path.
import { resolve } from 'path';
public getValidFileToUpload(): string {
return resolve('src/assets/validFilePath/testFile.csv');
}
Solution 5 - Javascript
If you are using a "dirent" type:
const path = require( "path" );
full_path = path.resolve( path_to_folder_containing__dir_ent__ , dir_ent.name );
Class: fs.Dirent https://nodejs.org/api/fs.html#fs_dirent_name
Module: fs.path https://nodejs.org/api/path.html