nodejs 读取外部文件显示在页面上实现方法

假设我们现在有一个 web.js文件和一个 1.html文件。

现在 web.js文件要读取 1.html文件里的类容 并且要把读取的内容显示在页面上
在这里插入图片描述
实现方法:

第一步

引入 http 核心模块和映入 读写文件 核心模块 (fs)

	let http = require('http')
	let fs = require('fs')

第二步

使用 http.createServer() 方法创建一个 WEB 服务器
	返回一个 server 实例

第三步

注册 request 请求事件
	server.on()
	request 请求事件处理函数,需要接受两个参数
		第一个参数 -> 请求对象:
			请求对象可以获取客户端的一些请求信息,列如路径(URL)
		第二个参数 -> 响应对象:
			就是请求完数据响应在页面上的信息
		
  server.on("request",function(req,res){
  let url = req.url
     if(url === "/"){
   		 res.setHeader('Content-Type','text/plain;charset=utf-8')
    	 res.end('初始数据请出入路径,来获取对应的数据')
   

		// 如果用户输入了 data 页面数据
	 } else if(url === "/data"){
    		/**
     		* 如果用户输入了 data 页面数据
     		*  1. 使用读文件 api -> fs.readFile
     		* 2.使用api ,error
     		*      函数里的回调 error,data。成功失败都返回什么
         	*      成功:
    	 	*      data: 数据
     		*      error: null

    		 *    失败:
    		 *    error: 错误对象
     		*    data: undefined (没有数据)
    	 */
    		fs.readFile('./1.html',function(error,data){

       			 if(error){

           	 res.setHeader('Content-Type','text/plain;charset=utf-8')
           	 res.end('文件读取失败,请检查代码')

    
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Node.js中,读写JSON文件有多种简单方法可以实现读取JSON文件: 1. 使用内置的fs模块的readFileSync函数来同步地读取JSON文件内容,并使用JSON.parse将其转换为对象或数组: ```javascript const fs = require('fs'); try { const data = fs.readFileSync('data.json', 'utf8'); const jsonData = JSON.parse(data); console.log(jsonData); } catch (error) { console.error(error); } ``` 2. 使用fs模块的readFile函数来异步读取JSON文件内容,并在回调函数中处理读取数据: ```javascript const fs = require('fs'); fs.readFile('data.json', 'utf8', (error, data) => { if (error) { console.error(error); } else { const jsonData = JSON.parse(data); console.log(jsonData); } }); ``` 写入JSON文件: 1. 使用fs模块的writeFileSync函数同步地写入JSON数据文件中: ```javascript const fs = require('fs'); const jsonData = { name: 'John Doe', age: 30, email: 'johndoe@example.com' }; try { fs.writeFileSync('data.json', JSON.stringify(jsonData, null, 2)); console.log('JSON data has been written to file.'); } catch (error) { console.error(error); } ``` 2. 使用fs模块的writeFile函数异步地写入JSON数据文件中: ```javascript const fs = require('fs'); const jsonData = { name: 'John Doe', age: 30, email: 'johndoe@example.com' }; fs.writeFile('data.json', JSON.stringify(jsonData, null, 2), (error) => { if (error) { console.error(error); } else { console.log('JSON data has been written to file.'); } }); ``` 以上是node.js读写JSON文件的简单方法。可以根据实际需求选择适合的方法

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值