Get full path to file in node.js

I have an application that uploads a csv file to a specific folder, say, uploads. Now I want to get the full path to this CSV file. E.g. D: \ MyNodeApp \ downloads \ Test.csv

How to get file location in node.js? I used multer to upload files.

Thank you in advance

+19
source share
5 answers

We can do very little with the information provided, but I will make a few assumptions:

  • Your “Uploads” folder is located inside your application’s folder.
  • The directory structure is very simple and fixed, so you have the application folder and one level lower, you have the "uploads" folder.

Then you can get the full path to these files, for example like this:

//index.js var filename = "myfile.csv"; ///you already have this one. var fullpath = __dirname + "/uploads/" + filename; 

That is, using the __dirname variable ( see the documents here ), you get the full path to the index.js file, and from there you can add the rest manually.

+11
source
 var path = require("path"); var absolutePath = path.resolve("Relative file path"); 

The dir structure, for example:

C: → WebServer-> Public-> Uploads-> MyFile.csv

and your working directory will be public, for example, path.resolve will 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 multi-platform and allows your application to work both on windows and on positioning machines.

+72
source

Assuming you are using multer with express, try this in your controller method:

 var path = require('path'); //gets your app 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) 
+3
source

In TypeScript, I did the following based on the relative path to the file.

 import { resolve } from 'path'; public getValidFileToUpload(): string { return resolve('src/assets/validFilePath/testFile.csv'); } 
0
source

Get all files from a folder and print a description of each file.

 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( testFolder, file ); log( "File : ", file ); log( "filename : ", filename ); log( "extname : ", extname ); log( "absolutePath : ", absolutePath); }); 
0
source

All Articles