2016-08-15 9 views
3

Согласно official document, createReadStream может принять тип буфера как пути аргумента.Как назначить буфер createReadStream

Но многие Q & только предлагает решение, как послать аргумент по строке, не буфера.

Как установить правильно буфер аргумент для удовлетворения пути из createReadStream?

Это мой код:

fs.access(filePath, (err: NodeJS.ErrnoException) => { 
    // Response with 404 
    if (Boolean(err)) { res.writeHead(404); res.end('Page not Found!'); return; } 

    // Create read stream accord to cache or path 
    let hadCached = Boolean(cache[filePath]); 
    if (hadCached) console.log(cache[filePath].content) 
    let readStream = hadCached 
     ? fs.createReadStream(cache[filePath].content, { encoding: 'utf8' }) 
     : fs.createReadStream(filePath); 
    readStream.once('open',() => { 
     let headers = { 'Content-type': mimeTypes[path.extname(lookup)] }; 
     res.writeHead(200, headers); 
     readStream.pipe(res); 
    }).once('error', (err) => { 
     console.log(err); 
     res.writeHead(500); 
     res.end('Server Error!'); 
    }); 

    // Suppose it hadn't cache, there is a `data` listener to store the buffer in cache 
    if (!hadCached) { 
     fs.stat(filePath, (err, stats) => { 
      let bufferOffset = 0; 
      cache[filePath] = { content: Buffer.alloc(stats.size, undefined, 'utf8') }; // Deprecated: new Buffer 

      readStream.on('data', function(chunk: Buffer) { 
       chunk.copy(cache[filePath].content, bufferOffset); 
       bufferOffset += chunk.length; 
       //console.log(cache[filePath].content) 
      }); 
     }); 
    } 
}); 

`` `

ответ

3

Используйте PassThrough метод из inbuild stream библиотеки:

const stream = require("stream"); 

let readStream = new stream.PassThrough(); 
readStream.end(new Buffer('Test data.')); 

// You now have the stream in readStream 
readStream.once("open",() => { 
    // etc 
});