Node.js初学第三天

时间:2021-09-02 20:53:53

一、Post提交

1、前端代码:

<!DOCTYPE HTML>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
			<form action="http://127.0.0.1:4050/dopost" method="post" enctype="multipart/form-data">
				姓名<input type="" name="name"   />
				<br />
				<input type="radio" name="sex" value="男" />男
				<input type="radio" name="sex" value="女" />女
				<br/>
				图片:<input type="file" name="imgs">
				<br/>
				<input type="submit" value="提交"/>
			</form>
	</body>
</html>

2、JS代码:

var formidable = require('formidable');//引用图片上传的包:https://www.npmjs.com/package/formidable
var  http = require('http');
var   util = require('util');
var fs = require("fs");
var sd = require("silly-datetime");
var path = require("path");
http.createServer(function(req,res){
    console.log(1);
    console.log(req.url);
    if (req.url == '/dopost' && req.method.toLowerCase() == 'post') {
        // parse a file upload
        var form = new formidable.IncomingForm();
        form.uploadDir = "./mydir";//设置图片保存路径
        form.parse(req, function(err, fields, files) {
            console.log(fields);
            console.log(files);
            res.writeHead(200, {'content-type': 'text/plain'});
            res.write('received upload:\n\n');
            res.end(util.inspect({fields: fields, files: files}));
           /*此段代码可实现更改图片名
            var ttt = sd.format(new Date(), 'YYYYMMDDHHmmss');
            var ran = parseInt(Math.random() * 89999 + 10000);
            var extname = path.extname(files.imgs.name);
            //执行改名
            var oldpath = __dirname + "/" + files.imgs.path;
            //新的路径由三个部分组成:时间戳、随机数、拓展名
            var newpath = __dirname + "/mydir/" + ttt + ran + extname;
            //改名
            fs.rename(oldpath,newpath,function(err){
                if(err){
                    throw Error("改名失败");
                }
                res.writeHead(200, {'content-type': 'text/plain'});
                res.end("成功");
            });*/
        });
        return;
    }
}).listen("4050","127.0.0.1");

3、输出结果如下:

{ name: '1', sex: '男' }
{ imgs: 
   File {
     domain: null,
     _events: {},
     _eventsCount: 0,
     _maxListeners: undefined,
     size: 178852,
     path: 'mydir\\upload_dc2eb054a1b78f04543fc2d273b2bd03',
     name: '1.gif',
     type: 'image/gif',
     hash: null,
     lastModifiedDate: Wed Aug 03 2016 11:17:57 GMT+0800 (中国标准时间),
     _writeStream: 
      WriteStream {
        _writableState: [Object],
        writable: true,
        domain: null,
        _events: {},
        _eventsCount: 0,
        _maxListeners: undefined,
        path: 'mydir\\upload_dc2eb054a1b78f04543fc2d273b2bd03',
        fd: null,
        flags: 'w',
        mode: 438,
        start: undefined,
        pos: undefined,
        bytesWritten: 178852,
        closed: true } } }

PS:1、formidable 是第三方模块,需要先在工作区安装(npm install formidable),网址:https://www.npmjs.com/package/formidable;

 二、模板引擎EJS

1、npm网址:https://www.npmjs.com/package/ejs,在本地安装ejs;

2、代码如下:

HTML代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>测试ejs(版本 <%= s  %></p>
</body>
</html>

JS代码:

var http=require("http");
var fs=require("fs");
var ejs=require("ejs");//引入ejs
http.createServer(function(req,res){
    //1.读取静态文件
    fs.readFile("./View/ejstest.html",function(err,data){
        if(err)
        {
            throw  err;
        }
        var content=data.toString();
        var data={
            s:"1.0"
        };
        var results=ejs.render(content,data);
        res.writeHead(200,{"Content-Type":"text/html;charset=UTF8"});
        res.end(results);
    });
}).listen("4050","127.0.0.1");

在浏览器中输入:http://127.0.0.1:4050/  运行结果:测试ejs(版本 1.0 )