前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >nodejs的引用和导出

nodejs的引用和导出

原创
作者头像
是小张啊喂
修改2021-06-24 14:30:27
5590
修改2021-06-24 14:30:27
举报
文章被收录于专栏:软件软件

首先需要了解两个关于的词

  • require 引用
  • export 导出

nodejs中 想引用一个文件 可以使用 require

例如:

代码语言:javascript
复制
// 操作文件
const file = require('fs')

// 创建 webserver 
const server = require('http')

正如我们想的那样,nodejs每次只能运行一个js脚本,所以如果想运行多个js脚本可以采用引用(require)的方式

代码语言:javascript
复制
// index.js
console.log('这个是 index.js')

// hello.js
console.log('这个是 hello.js')
require('./index')

// 运行 
$ node hello.js

那如何调用index.js中的属性和方法呢?这个时候就需要导出这些属性和方法

代码语言:javascript
复制
// index.js
exports.name = '张三'

exports.add = function (x, y){
    return x + y
}

// hello.js
const index =  require('./index')

console.log(index.name)

console.log(index.add(2, 3))
读取网页信息文本
代码语言:javascript
复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index.html</title>
    <style type="text/css" > h1 { color: aqua }</style>
</head>
<body>
    <h1>这里是 index.html 页面</h1>
</body>
</html>
  • nodejs读取html显示
代码语言:javascript
复制
const http = require('http')
const file = require('fs')

const server = http.createServer();

server.on('request', function (request, response) {
    let url = request.url;

    if (url == '/') {
        file.readFile('./resource/index.html', function (error, data) {
            if (error != null) {
                response.setHeader('Content-Type', 'text/plain;charset=utf-8')
                response.end('file dons not exits or read fail')
            }
            response.setHeader('Content-Type', 'text/html;charset=utf-8')
            response.end(data)
        })
    }
})

server.listen('8081', function () {
    console.log('Server running at http://127.0.0.1:8081/');
})

nodejs 响应文件到页面,需要设置响应的文件类型

喜欢编程的,请关注我的博客https://www.lzmvlog.top/

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 读取网页信息文本
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档