发送响应后,删除临时文件的正确方法

时间:2016-08-19 05:41:32

标签: node.js express httpresponse

我有一个简单的基于Express 4的API,它输出一个MP3文件,该文件是根据一些提供的参数生成的。但是,在响应发出后,我似乎无法删除此临时MP3文件。

我有什么:

app.get('/endpoint', function(request, response) {

  // Distill parameters from request and create tempFileMp3  

  var stat = Fs.statSync(tempFileMp3);

  response.writeHead(status, {
    'Content-Type': 'audio/mpeg',
    'Content-Length': stat.size
  });

  stream = Fs.createReadStream(tempFileMp3);
  stream.pipe(response);
});

首先,我希望能够删除tempFileMp3事件streamend事件中的finish

stream
  .on('end', function() {
    Fs.unlinkSync(tempFileMp3);
  })
  .on('close', function() {
    Fs.unlinkSync(tempFileMp3);
  })
;

但是endclose事件都没有被解雇。

如何在发送响应后删除临时MP3文件?

1 个答案:

答案 0 :(得分:1)

尝试捕获响应完成:

import numpy as np
import pandas as pd
from scipy import signal
import matplotlib.pyplot as plt
def sine_generator(fs, sinefreq, duration):
    T = duration
    nsamples = fs * T
    w = 2. * np.pi * sinefreq
    t_sine = np.linspace(0, T, nsamples, endpoint=False)
    y_sine = np.sin(w * t_sine)
    result = pd.DataFrame({ 
        'data' : y_sine} ,index=t_sine)
    return result

def butter_highpass(cutoff, fs, order=5):
    nyq = 0.5 * fs
    normal_cutoff = cutoff / nyq
    b, a = signal.butter(order, normal_cutoff, btype='high', analog=False)
    return b, a

def butter_highpass_filter(data, cutoff, fs, order=5):
    b, a = butter_highpass(cutoff, fs, order=order)
    y = signal.filtfilt(b, a, data)
    return y

fps = 30
sine_fq = 10 #Hz
duration = 10 #seconds
sine_5Hz = sine_generator(fps,sine_fq,duration)
sine_fq = 1 #Hz
duration = 10 #seconds
sine_1Hz = sine_generator(fps,sine_fq,duration)

sine = sine_5Hz + sine_1Hz

filtered_sine = butter_highpass_filter(sine.data,10,fps)

plt.figure(figsize=(20,10))
plt.subplot(211)
plt.plot(range(len(sine)),sine)
plt.title('generated signal')
plt.subplot(212)
plt.plot(range(len(filtered_sine)),filtered_sine)
plt.title('filtered signal')
plt.show()