搭建node服务器

搭建node远程服务器

1. 在根目录下安装node稳定版

QQ截图20170907110449.png

2. 创建服务器

image.png
var http = require('http');
var formidable = require('formidable');
var fs = require('fs');
var path = require('path')
var Util = require('./util.js')

http.createServer(function(req, res) {
    if (req.url == '/fileupload') {
        var form = new formidable.IncomingForm();
        form.parse(req, function(err, fields, files) {
            var oldpath = files.filetoupload.path;
            var newpath = '/home/qiuzhilin/www/blue-pi-upload.tianqi.cn/upload/' + files.filetoupload.name;
            fs.rename(oldpath, newpath, function(err) {
                if (err) throw err;
                // 获取文件名
                var txtname = path.basename(newpath);
                var basename = path.basename(newpath,'.txt')
                // 获取网络路径
                oldpath = path.join('https://blue-pi-upload.tianqi.cn/upload/',txtname)
                res.write(oldpath);
                // 读取文件内容
                fs.readFile(newpath, (err, data) => {
                  if (err) throw err;
                  data = data.toString()
                  data = Util.formateData(data)
                  data = JSON.stringify(data)
                  fs.writeFile('../blue-pi-upload.tianqi.cn/upload/json/' + basename + '.json' , data, (err) => {
                    if (err) throw err;
                    console.log('The file has been saved!');
                  });
                });
                res.end();
            });
        });
    } else {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
        res.write('<input type="file" name="filetoupload"><br>');
        res.write('<input type="submit">');
        res.write('</form>');
        return res.end();
    }
}).listen(10087);

3. 运行服务器

  • 打开Xshell,进入服务器
  • node ~/demo.js

4. 打开chrome,地址栏http://IP:10087/

image.png

5. 文件上传到

image.png

6. 访问https://blue-pi-upload.tianqi.cn/upload/json/hainan.json获取数据

image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容