53

从 http函数进行了简单的下载,如下所示(为简化起见,省略了错误处理):

function download(url, tempFilepath, filepath, callback) {
    var tempFile = fs.createWriteStream(tempFilepath);
    http.request(url, function(res) {
        res.on('data', function(chunk) {
            tempFile.write(chunk);
        }).on('end', function() {
            tempFile.end();
            fs.renameSync(tempFile.path, filepath);
            return callback(filepath);
        })
    });
}

但是,由于我download()异步调用了数十次,它很少在fs.renameSync抱怨找不到文件时报告错误tempFile.path

Error: ENOENT, no such file or directory 'xxx'

我使用相同的 url 列表来测试它,它失败了大约 30% 的时间。一个一个下载时,相同的 url 列表有效。

再测试一番,发现如下代码

fs.createWriteStream('anypath');
console.log(fs.exist('anypath'));
console.log(fs.exist('anypath'));
console.log(fs.exist('anypath'));

并不总是打印true,但有时会打印第一个答案false

我怀疑太多的异步fs.createWriteStream调用不能保证文件的创建。这是真的?有什么方法可以保证文件的创建吗?

4

4 回答 4

74

在您从流中接收到事件之前,您不应该调用write您的tempFile写入流。'open'在您看到该事件之前,该文件将不存在。

对于您的功能:

function download(url, tempFilepath, filepath, callback) {
    var tempFile = fs.createWriteStream(tempFilepath);
    tempFile.on('open', function(fd) {
        http.request(url, function(res) {
            res.on('data', function(chunk) {
                tempFile.write(chunk);
            }).on('end', function() {
                tempFile.end();
                fs.renameSync(tempFile.path, filepath);
                return callback(filepath);
            });
        });
    });
}

对于您的测试:

var ws = fs.createWriteStream('anypath');
ws.on('open', function(fd) {
    console.log(fs.existsSync('anypath'));
    console.log(fs.existsSync('anypath'));
    console.log(fs.existsSync('anypath'));
});
于 2012-10-16T02:42:34.567 回答
19

接受的答案没有为我下载一些最后的字节。
这是一个可以正常工作的Q版本(但没有临时文件)。

'use strict';

var fs = require('fs'),
    http = require('http'),
    path = require('path'),
    Q = require('q');

function download(url, filepath) {
  var fileStream = fs.createWriteStream(filepath),
      deferred = Q.defer();

  fileStream.on('open', function () {
    http.get(url, function (res) {
      res.on('error', function (err) {
        deferred.reject(err);
      });

      res.pipe(fileStream);
    });
  }).on('error', function (err) {
    deferred.reject(err);
  }).on('finish', function () {
    deferred.resolve(filepath);
  });

  return deferred.promise;
}

module.exports = {
  'download': download
};

注意我正在收听finish文件流而不是end响应。

于 2013-12-11T12:25:47.233 回答
1

这是我用来完成它的方法:

function download(url, dest) {
    return new Promise((resolve, reject) => {
        http.get(url, (res) => {
            if (res.statusCode !== 200) {
                var err = new Error('File couldn\'t be retrieved');
                err.status = res.statusCode;
                return reject(err);
            }
            var chunks = [];
            res.setEncoding('binary');
            res.on('data', (chunk) => {
                chunks += chunk;
            }).on('end', () => {
                var stream = fs.createWriteStream(dest);
                stream.write(chunks, 'binary');
                stream.on('finish', () => {
                    resolve('File Saved !');
                });
                res.pipe(stream);
            })
        }).on('error', (e) => {
            console.log("Error: " + e);
            reject(e.message);
        });
    })
};
于 2018-02-08T16:25:43.200 回答
0

我正在通过 nodejsrequest-promiserequest库上传和下载文件(docx、pdf、文本等)。

问题request-promise是他们没有从包中承诺pipe方法。request因此,我们需要以旧的方式来做。

我能够提出混合解决方案,我可以同时使用async/awaitPromise()。这是示例:

    /**
     * Downloads the file.
     * @param {string} fileId : File id to be downloaded.
     * @param {string} downloadFileName : File name to be downloaded.
     * @param {string} downloadLocation : File location where it will be downloaded.
     * @param {number} version : [Optional] version of the file to be downloaded.
     * @returns {string}: Downloaded file's absolute path.
     */
    const getFile = async (fileId, downloadFileName, downloadLocation, version = undefined) => {
        try {
            const url = version ? `http://localhost:3000/files/${fileId}?version=${version}` : 
`${config.dms.url}/files/${fileUuid}`;
            const fileOutputPath = path.join(downloadLocation, fileName);

            const options = {
                method: 'GET',
                url: url,
                headers: {
                    'content-type': 'application/json',
                },
                resolveWithFullResponse: true
            }

            // Download the file and return the full downloaded file path.
            const downloadedFilePath = writeTheFileIntoDirectory(options, fileOutputPath);

            return downloadedFilePath;
        } catch (error) {
           console.log(error);
        }
    };

正如您在上面的getFile方法中看到的,我们正在使用 ES 支持的最新async/await功能进行异步编程。现在,让我们看看writeTheFileIntoDirectory方法。

/**
 * Makes REST API request and writes the file to the location provided.
 * @param {object} options : Request option to make REST API request.
 * @param {string} fileOutputPath : Downloaded file's absolute path.
 */
const writeTheFileIntoDirectory = (options, fileOutputPath) => {
    return new Promise((resolve, reject) => {
        // Get file downloaded.
        const stream = fs.createWriteStream(fileOutputPath);
        return request
            .get(options.url, options, (err, res, body) => {
                if (res.statusCode < 200 || res.statusCode >= 400) {
                    const bodyObj = JSON.parse(body);
                    const error = bodyObj.error;
                    error.statusCode = res.statusCode;
                    return reject(error);
                }
            })
            .on('error', error => reject(error))
            .pipe(stream)
            .on('close', () => resolve(fileOutputPath));
    });
}

nodejs 的美妙之处在于它支持不同异步实现的向后兼容。如果一个方法正在返回 Promise,那么await将被踢入并等待该方法完成。

上述writeTheFileIntoDirectory方法会下载文件并在流关闭成功时返回正向,否则返回错误。

于 2019-09-23T19:55:51.967 回答