搭建node遠(yuǎn)程服務(wù)器
1. 在根目錄下安裝node穩(wěn)定版
QQ截圖20170907110449.png
2. 創(chuàng)建服務(wù)器
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')
// 獲取網(wǎng)絡(luò)路徑
oldpath = path.join('https://blue-pi-upload.tianqi.cn/upload/',txtname)
res.write(oldpath);
// 讀取文件內(nèi)容
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. 運(yùn)行服務(wù)器
- 打開(kāi)Xshell,進(jìn)入服務(wù)器
- node ~/demo.js
4. 打開(kāi)chrome枫吧,地址欄http://IP:10087/
image.png
5. 文件上傳到
image.png
6. 訪問(wèn)https://blue-pi-upload.tianqi.cn/upload/json/hainan.json獲取數(shù)據(jù)
image.png