Aldo
Aldo

Reputation: 1

NodeJs - Error while reading files using fs.createReadStream

I am trying to implement a feature to my web app where you can upload CSV files and insert data into Postgresql. I have made my app endpoint and written some code


    const router = require('express').Router()
    const uploadMid = require('./fileUpMid')
    const pool = require('./db')
    
    
    const fs = require("fs");
    const fastcsv = require("fast-csv");
    
    const upload = async (req, res) => {
        if (req.files === null) {
            return res.status(400).json({ msg: 'No file uploaded' });
        }
    
        const file = req.files.file;
    
        file.mv(`${__dirname}/uploads/${file.name}`, err => {
            if (err) {
                console.error(err);
                return res.status(500).send(err);
            }
            res.json({ fileName: file.name, filePath: `/uploads/${file.name}` });
        });
    
        let persons = [];
        let path = __dirname + "/uploads/" +file.name;
    
        fs.createReadStream(path)
            .pipe(fastcsv.parse({ headers: true }))
            .on("error", (error) => {
                console.error(error.message);
            })
            .on("data", (row) => {
                persons.push(row);   
            })
            .on("end", () => {
                //remove head
                persons.shift();
    
                const q = "some query here";
    
                pool.connect((err, client, done) => {
                    if (err) throw err;
                    
    
                    try {
                        persons.forEach(row => {
                            console.log(typeof row)
                            var obj = JSON.parse(JSON.stringify(row));
                            var values = Object.keys(obj).map(function (key) { return obj[key]; });
                            console.log(values)
                            client.query(q, values, (err, res) => {
    
                                if (err) {
                                    console.log(err.stack);
                                } else {
                                    console.log("inserted " + res.rowCount + " row:", row);
                                }
                            });
                        });
                    } finally {
                        done();
                    }
                });
            })
        // fs.unlinkSync(path)
            
    }
    
    
    router.post('/file', uploadMid.single("file") ,upload)
    
    module.exports = router

Everything seemed to work fine, but when I try to upload a second file I awlways get an error on terminal

Error: ENOENT: no such file or directory, open 'filename here with full path'

>- Emitted 'error' event on ReadStream instance at: 
>- at internal/fs/streams.js:126:14
>- at FSReqCallback.oncomplete (fs.js:180:23) {
>- errno: -4058,
>- code: 'ENOENT',
>- syscall: 'open',
>- path: 'filename here with full path'}

I know this is not a safe nor secure way to upload data but this app is intended to be run only locally. Even when the first file is upload successfully in DevTools console it logs

GET http://localhost:3000/uploads/filename [HTTP/1.1 404 Not Found 8ms]

But the file is created with all its content on uploads directory. Any tip for what to look for ?

Thank you in advance :)

Upvotes: 0

Views: 2243

Answers (1)

ypahalajani
ypahalajani

Reputation: 800

Judging by the error (Error: ENOENT: no such file or directory, open 'filename here with full path'), here is the suggested way of defining paths in NodeJS apps using the path module.

const path = require('path');

// Inside`upload` middleware
const filePath = path.join(__dirname, 'uploads', file.name);

Upvotes: 1

Related Questions