首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用nodejs服务镜像

如何使用nodejs服务镜像
EN

Stack Overflow用户
提问于 2011-04-29 03:08:37
回答 7查看 333.8K关注 0票数 179

我有一个驻留在public/images/logo.gif的徽标。这是我的nodejs代码。

代码语言:javascript
复制
http.createServer(function(req, res){
  res.writeHead(200, {'Content-Type': 'text/plain' });
  res.end('Hello World \n');
}).listen(8080, '127.0.0.1');

它可以工作,但当我请求localhost:8080/logo.gif时,我显然得不到徽标。

我需要做哪些更改才能为镜像服务。

EN

回答 7

Stack Overflow用户

发布于 2018-06-24 21:51:13

代码语言:javascript
复制
var http = require('http');
var fs = require('fs');

http.createServer(function(req, res) {
  res.writeHead(200,{'content-type':'image/jpg'});
  fs.createReadStream('./image/demo.jpg').pipe(res);
}).listen(3000);
console.log('server running at 3000');
票数 23
EN

Stack Overflow用户

发布于 2017-05-14 02:56:52

太晚了,但帮助了别人,我在用node version v7.9.0express version 4.15.0

如果你的目录结构是这样的:

代码语言:javascript
复制
your-project
   uploads
   package.json
   server.js

server.js代码:

代码语言:javascript
复制
var express         = require('express');
var app             = express();
app.use(express.static(__dirname + '/uploads'));// you can access image 
 //using this url: http://localhost:7000/abc.jpg
//make sure `abc.jpg` is present in `uploads` dir.

//Or you can change the directory for hiding real directory name:

`app.use('/images', express.static(__dirname+'/uploads/'));// you can access image using this url: http://localhost:7000/images/abc.jpg


app.listen(7000);
票数 16
EN

Stack Overflow用户

发布于 2014-09-25 04:03:12

请求的Vanilla节点版本:

代码语言:javascript
复制
var http = require('http');
var url = require('url');
var path = require('path');
var fs = require('fs');

http.createServer(function(req, res) {
  // parse url
  var request = url.parse(req.url, true);
  var action = request.pathname;
  // disallow non get requests
  if (req.method !== 'GET') {
    res.writeHead(405, {'Content-Type': 'text/plain' });
    res.end('405 Method Not Allowed');
    return;
  }
  // routes
  if (action === '/') {
    res.writeHead(200, {'Content-Type': 'text/plain' });
    res.end('Hello World \n');
    return;
  }
  // static (note not safe, use a module for anything serious)
  var filePath = path.join(__dirname, action).split('%20').join(' ');
  fs.exists(filePath, function (exists) {
    if (!exists) {
       // 404 missing files
       res.writeHead(404, {'Content-Type': 'text/plain' });
       res.end('404 Not Found');
       return;
    }
    // set the content type
    var ext = path.extname(action);
    var contentType = 'text/plain';
    if (ext === '.gif') {
       contentType = 'image/gif'
    }
    res.writeHead(200, {'Content-Type': contentType });
    // stream the file
    fs.createReadStream(filePath, 'utf-8').pipe(res);
  });
}).listen(8080, '127.0.0.1');
票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5823722

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档