創(chuàng)建自己的module
1.創(chuàng)建文件: touch myFirstModule.js
,寫入:
exports.myDateTime = function() {
return Date();
}
通過exports
關(guān)鍵字來導(dǎo)出自己的module.
2.在helloWorld.js
中引入自己的module:
var http = require('http');
var myDate = require('./myFirstModule.js');
http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("The date and time are currently: " + myDate.myDateTime());
res.end();
}).listen(8080);
3.命令行中輸入: node helloWorld.js
, 然后在瀏覽器中打開http://localhost:8080/
得到如下:
說明成功引入了模塊并使用拒秘。
HTTP Module
1.req.url: 用來表示url中domain之后的部分闺骚,對helloWorld.js
中的代碼做修改:
var http = require('http');
var myDate = require('./myFirstModule.js');
http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(req.url);
res.end();
}).listen(8080);
訪問http://localhost:8080/summer
得到如下結(jié)果:
File System Module
nodeJs中的File System Module對文件進行讀彤钟,創(chuàng)建拿霉,更新曹体,刪除扳缕,重命名操作。
文件的讀取
1.通過var fs = require('fs');
來引入該module
2.touch demoFile1.html
生成一個文件來作為被操作的文件举畸,寫入以下內(nèi)容:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>Header</h1>
<p>My paragraph</p>
</body>
</html>
3.touch readFileDemo.js
查排,寫入以下內(nèi)容:
var http = require('http');
var fs = require('fs');
http.createServer(function(req, res) {
fs.readFile('./demoFile1.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
})
}).listen(8080);
4.命令行中輸入node readFileDemo.js
- 訪問
http://localhost:8080/
,得到以下:
文件的創(chuàng)建
fs.open()
fs.appendFile()
fs.writeFile()
以上三個方法在操作文件時抄沮,如果目標文件不存在跋核,則會創(chuàng)建一個新的文件
更新文件
1.fs.appendFile()
:該方法用來在文件的最后添加指定的內(nèi)容
var fs = require('fs');
fs.appendFile('mynewfile1.txt', ' This is my text.', function (err) {
if (err) throw err;
console.log('Updated!');
});
2.fs.writeFile()
: 該方法用來重寫文件
var fs = require('fs');
fs.writeFile('mynewfile3.txt', 'This is my text', function (err) {
if (err) throw err;
console.log('Replaced!');
});
刪除文件
fs.unlink()
:
var fs = require('fs');
fs.unlink('mynewfile2.txt', function (err) {
if (err) throw err;
console.log('File deleted!');
});
重命名文件
fs.rename()
:
var fs = require('fs');
fs.rename('mynewfile1.txt', 'myrenamedfile.txt', function (err) {
if (err) throw err;
console.log('File Renamed!');
});