javascript开发后端程序的神器nodejs

前端开发 作者: 2024-08-21 11:25:01
简介 javascript虽然一直都可以做服务端编程语言,但是它更多的是以客户端编程语言来展示在世人面前的。也许javascript自己都忘记了还可以做服务器端编程,直到2009年nodejs的横空出

简介

nodejs的历史

nodejs简介

const http = require('http')

const hostname = '127.0.0.1'
const port = 3000

const server = http.createServer((req,res) => {
  res.statusCode = 200
  res.setHeader('Content-Type','text/plain')
  res.end('welcome to www.flydean.com\n')
})

server.listen(port,hostname,() => {
  console.log(`please visit http://${hostname}:${port}/`)
})
  • request 是一个http.IncomingMessage对象,提供了请求的详细信息。
  • response 是一个http.ServerResponse对象,用于返回数据给调用方。

nodejs的运行环境

node app.js
node
Welcome to Node.js v12.13.1.
Type ".help" for more information.
>
> console.log('www.flydean.com');
www.flydean.com
> http
{
  _connectionListener: [Function: connectionListener],METHODS: [
    'ACL','BIND','CHECKOUT','CONNECT','COPY','DELETE','GET','HEAD','LINK','LOCK','M-SEARCH','MERGE','MKACTIVITY','MKCALENDAR','MKCOL','MOVE','NOTIFY','OPTIONS','PATCH','POST','PROPFIND','PROPPATCH','PURGE','PUT','REBIND','REPORT','SEARCH','SOURCE','SUBSCRIBE','TRACE','UNBIND','UNLINK','UNLOCK','UNSUBSCRIBE'
  ],STATUS_CODES: {
    '100': 'Continue','101': 'Switching Protocols','102': 'Processing','103': 'Early Hints','200': 'OK','201': 'Created','202': 'Accepted','203': 'Non-Authoritative Information','204': 'No Content','205': 'Reset Content','206': 'Partial Content','207': 'Multi-Status','208': 'Already Reported','226': 'IM Used','300': 'Multiple Choices','301': 'Moved Permanently','302': 'Found','303': 'See Other','304': 'Not Modified','305': 'Use Proxy','307': 'Temporary Redirect','308': 'Permanent Redirect','400': 'Bad Request','401': 'Unauthorized','402': 'Payment Required','403': 'Forbidden','404': 'Not Found','405': 'Method Not Allowed','406': 'Not Acceptable','407': 'Proxy Authentication Required','408': 'Request Timeout','409': 'Conflict','410': 'Gone','411': 'Length Required','412': 'Precondition Failed','413': 'Payload Too Large','414': 'URI Too Long','415': 'Unsupported Media Type','416': 'Range Not Satisfiable','417': 'Expectation Failed','418': "I'm a Teapot",'421': 'Misdirected Request','422': 'Unprocessable Entity','423': 'Locked','424': 'Failed Dependency','425': 'Unordered Collection','426': 'Upgrade Required','428': 'Precondition Required','429': 'Too Many Requests','431': 'Request Header Fields Too Large','451': 'Unavailable For Legal Reasons','500': 'Internal Server Error','501': 'Not Implemented','502': 'Bad Gateway','503': 'Service Unavailable','504': 'Gateway Timeout','505': 'HTTP Version Not Supported','506': 'Variant Also Negotiates','507': 'Insufficient Storage','508': 'Loop Detected','509': 'Bandwidth Limit Exceeded','510': 'Not Extended','511': 'Network Authentication Required'
  },Agent: [Function: Agent] { defaultMaxSockets: Infinity },ClientRequest: [Function: ClientRequest],IncomingMessage: [Function: IncomingMessage],OutgoingMessage: [Function: OutgoingMessage],Server: [Function: Server],ServerResponse: [Function: ServerResponse],createServer: [Function: createServer],get: [Function: get],request: [Function: request],maxHeaderSize: [Getter],globalAgent: [Getter/Setter]
}
> http.
http.__defineGetter__      http.__defineSetter__      http.__lookupGetter__      http.__lookupSetter__      http.__proto__             http.constructor
http.hasOwnProperty        http.isPrototypeOf         http.propertyIsEnumerable  http.toLocaleString        http.toString              http.valueOf

http.Agent                 http.ClientRequest         http.IncomingMessage       http.METHODS               http.OutgoingMessage       http.STATUS_CODES
http.Server                http.ServerResponse        http._connectionListener   http.createServer          http.get                   http.globalAgent
http.maxHeaderSize         http.request
> .help
.break    Sometimes you get stuck,this gets you out
.clear    Alias for .break
.editor   Enter editor mode
.exit     Exit the repl
.help     Print this help message
.load     Load JS from a file into the REPL session
.save     Save all evaluated commands in this REPL session to a file

process

process.exit(0)
process.on('SIGTERM',() => {
  server.close(() => {
    console.log('进程已终止')
  })
})
process.kill(process.pid,'SIGTERM')
process.env.NODE_ENV // "development"
node app.js joe
const args = process.argv.slice(2)
args[0]
node app.js --name=joe

const args = require('minimist')(process.argv.slice(2))
args['name'] //joe
const readline = require('readline').createInterface({
  input: process.stdin,output: process.stdout
})

readline.question(`how are you?`,answer => {
  console.log(`${answer}!`)
  readline.close()
})
const inquirer = require('inquirer')

var questions = [
  {
    type: 'input',name: 'hello',message: "how are you?"
  }
]

inquirer.prompt(questions).then(answers => {
  console.log(`${answers['hello']}!`)
})

exports模块

module.exports = class Square {
  constructor(width) {
    this.width = width;
  }

  area() {
    return this.width ** 2;
  }
};
const Square = require('./square.js');
const mySquare = new Square(2);
console.log(`mySquare 的面积是 ${mySquare.area()}`);
const { PI } = Math;

exports.area = (r) => PI * r ** 2;

exports.circumference = (r) => 2 * PI * r;
const circle = require('./circle.js');
console.log(`半径为 4 的圆的面积是 ${circle.area(4)}`);

nodejs API

nodejs的框架

原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_66064.html