0

I have simple app where I upload .pdf file then using qpdf to encrypt it.

There is my 'put' route in express.

app.put('/files', (req, res) => {
  const file = req.body;
  const base64data = file.content.replace(/^data:.*,/, '');
  //make temp dir
  fs.mkdtemp(path.join(os.tmpdir(), 'foo-'), (err, folder) => {
    if (err) throw err;
    console.log(folder);
    //write file to local and temp
    fs.writeFile(folder +'/' + file.name, base64data, 'base64', (err) => {
    if (err) {
      console.log(err);
      res.sendStatus(500);
    } else {
      res.set('Location', folder +'/' + file.name);
      res.status(200);
      console.log('test: ' + folder +'/' +file.name);

      res.send(file);

      // paths
      const src: any = (userFiles + file.name);
      const dst: any = (folder + '/' + file.name);

      //gen password and encrypt pdf
      genPass(dst, src);

      //List files from temp dir
      // const filesInDir = fs.readdirSync(folder, { withFileTypes: true })
      //   .filter(item => !item.isDirectory())
      //   .map(item => item.name)

      //   console.log('files from tmp dir: '+filesInDir)
    }
  });
  });
});

I am doing here almost everything. First gen. temp dir then write file to local and temp and then gen password and ecnrypt pdf. This all works fine.

But now I need to make get response to list all files.

I tried to do something like this

app.get('/files', function (req,res) {
  const filesInDir = fs.readdirSync(folder, { withFileTypes: true })
    .filter(item => !item.isDirectory())
    .map(item => item.name)

  console.log('files from tmp dir: ' + filesInDir)
});

but got error:

Cannot find name 'folder'

of course because 'folder' is inside app.put

how can I "export" this folder variable to app.get?

Folder got path to temp directory.

Kurt Hamilton
  • 12,490
  • 1
  • 24
  • 40
Marcin Domorozki
  • 51
  • 1
  • 3
  • 12

1 Answers1

0

In order to share data between routes

app.post('/files', function(req, res){
  app.set('filePath', dst);
});
app.get('/files', function(req, res) {
  app.get('filePath');
});

For reference use this link

Noob Coder
  • 444
  • 1
  • 5
  • 16
  • depends on your business requirement, I only answered your question *how can I "export" this folder variable to app.get?* – Noob Coder Mar 10 '20 at 10:20