//模块 var obj = require('./count.js'); console.log(obj.arr); console.log(obj.adder(3,2)); console.log('there is ' + obj.arr.length + ' fruits in the packet');
count.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14
var arr = ['apple', 'banana', 'orange'];
var adder = function(a,b) { return`this result is ${a+b}`; }
//事件核心库 var events = require('events'); //新增事件 var myEmitter = new events.EventEmitter(); //给事件绑定函数 myEmitter.on('someEvent', function(message) { console.log(message); }) //触发事件 myEmitter.emit('someEvent', 'the event was emmited');
var http = require('http'); var server = http.createServer(function(request, response) { response.writeHead(200, { 'Content-Type': 'text/plain'}); //response.write('Hello from out application'); response.end('Hello from out application'); }) server.listen(3000, '127.0.0.1');
var http = require('http'); var onRequest = function(request, response) { response.writeHead(200, { 'Content-Type': 'text/plain'}); //response.write('Hello from out application'); response.end('Hello world'); } var server = http.createServer(onRequest); server.listen(3000, '127.0.0.1'); console.log('Server started at ls port:3000'); ```
传入json对象:
``` js var http = require('http'); var onRequest = function(request, response) { response.writeHead(200, { 'Content-Type': 'text/json'}); //response.write('Hello from out application'); var myObj = { name: 'sasbfhad', job: 'coder', age: '21' }; response.end(JSON.stringify(myObj)); } var server = http.createServer(onRequest); server.listen(3000, '127.0.0.1'); console.log('Server started at ls port:3000'); ```
传html:
``` js var http = require('http'); var fs = require('fs'); var onRequest = function(request, response) { response.writeHead(200, { 'Content-Type': 'text/html'}); //response.write('Hello from out application'); var myReadStream = fs.createReadStream(__dirname + '/shiyan.html', 'utf8'); myReadStream.pipe(response); }
var server = http.createServer(onRequest); server.listen(3000, '127.0.0.1'); console.log('Server started at ls port:3000');
封装:
app.js
1 2
var server = require('./server'); server.startServer();
server.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
var http = require('http'); var fs = require('fs'); functionstartServer() { var onRequest = function(request, response) { response.writeHead(200, { 'Content-Type': 'text/plain'}); //response.write('Hello from out application'); var myReadStream = fs.createReadStream(__dirname + '/shiyan.html', 'utf8'); myReadStream.pipe(response); }
var server = http.createServer(onRequest); server.listen(3000, '127.0.0.1'); console.log('Server started at ls port:3000'); }