分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 教程案例

node.js(一)

发布时间:2023-09-06 02:20责任编辑:苏小强关键词:js

安装官网:

https://nodejs.org/en/

  运行代码:

var http=require(‘http‘)http.createServer(function(req,res){ ???res.writeHead(200,{‘Content-Type‘:‘text/html‘}); ???res.write(‘<h1>Node.js</h1>‘); ???res.end(‘<p>PCAT</p>‘);}).listen(3000);console.log(‘HTTP server is listening at port 3000.‘);

  建立app.js 用cmd启动,出现成功

HTTP server is listening at port 3000.

  安装调试工具:

npm install -g supervisor

  用supervisor启动服务,每次修改代码就不用node启动了。

supervisor app.js ??文件名称

  同步读取文件:

var fs=require(‘fs‘);var data=fs.readFileSync(‘file.txt‘,‘UTF-8‘);console.log(data);console.log(‘end‘);

  

异步读取文件:

var fs=require(‘fs‘);fs.readFile(‘file.txt‘,‘UTF-8‘,function(err,data){ ???if(err){ ???????console.log(‘read file err‘); ???}else{ ???????console.log(data); ???}});console.log(‘end‘);

  

写一个简单的自定义事件:

var EventEmitter=require(‘events‘).EventEmitter;var event=new EventEmitter();event.on(‘some_event‘,function(){ ???console.log(‘这是一个自定义事件‘);});setTimeout(function(){ ???event.emit(‘some_event‘);},1000);

  

自定义模块(调用):

var myModule=require(‘./module‘);myModule.setName(‘marico‘);myModule.sayHello();

  模块:

var name;exports.setName=function(thyName){name=thyName;}exports.sayHello=function(){console.log(‘hello‘+name);}

  

把上面的方法分装一下:

function hello(){ ???var name; ???this.setName=function(thyName){ ???????name=thyName; ???} ???this.sayHello=function(){ ???????console.log(‘hello ‘+name); ???}}//exports.hello=hello;module.exports=hello;

  

var hello=require(‘./module.js‘);var he=new hello();he.setName(‘marico‘);he.sayHello();var he2=new hello();he2.setName(‘yfc‘);he2.sayHello();

  

node.js(一)

原文地址:https://www.cnblogs.com/sunliyuan/p/9901556.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved