Get full file path in Node.js

Javascriptnode.js

Javascript 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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionImCoderView Question on Stackoverflow
Solution 1 - JavascriptAnton StafeyevView Answer on Stackoverflow
Solution 2 - JavascriptM. Hamza RajputView Answer on Stackoverflow
Solution 3 - JavascripthassansinView Answer on Stackoverflow
Solution 4 - JavascriptAlferd NobelView Answer on Stackoverflow
Solution 5 - JavascriptKANJICODERView Answer on Stackoverflow