• node.js系统模块


    系统模块

    1.什么是系统模块

    node运行环境提供的API

    2.系统模块fs文件操作

    1.读取文件内容readFile()方法

    // 1.通过模块的名字fs对模块进行引用
    1.const fs = require('fs');
    
    // 2.通过模块内部的readFile读取文件内容
    fs.readFile('./01.helloworld.js', 'utf8', (err, doc) => {
    	// 如果文件读取出错err 是一个对象 包含错误信息
    	// 如果文件读取正确 err是 null
    	// doc 是文件读取的结果
    	console.log(err);
    	console.log(doc);
    });
    

    2.写入文件内容 writeFile()方法

    const fs = require('fs');
    
    fs.writeFile('./demo.txt', '即将要写入的内容', err => {
    	if (err != null) {
    		console.log(err);
    		return;
    	}
    
    	console.log('文件内容写入成功');
    })
    

    3.路径拼接语法 join()方法

    // public/uploads/avatar
    const path = require('path');
    
    const finalPath = path.join('public', 'uploads','avatar');
    
    console.log(finalPath); //publicuploadsavatar
    

    4.相对路径和绝对路径
    大部分情况使用相对路径,在读取文件或设置文件路径是使用绝对路径
    使用__dirname获取当前文件所在位置的绝对路径

    const fs = require('fs');
    const path = require('path');
    
    console.log(__dirname); //D:code
    ode
    ode.js day01
    console.log(path.join(__dirname, '01.helloworld.js')) //D:code
    ode
    ode.js day011.helloworld.js
    
    fs.readFile(path.join(__dirname, '01.helloworld.js'), 'utf8', (err, doc) => {
    	console.log(err) //null
    	console.log(doc) //整个01.helloworld.js内容
    });
    
  • 相关阅读:
    django admin site配置(二)
    MyEclipse中无法将SVN检出来的项目部署到tomcat中
    遍历目录树,清理编译目录
    axis2学习, ant 构建axis2 ws
    [置顶] 2013 Multi-University Training Contest 8
    Cocos2d-x 关于在iOS平台真机测试的一些注意
    SharePoint 2013的100个新功能之社交
    路由共享上网原理
    red ant
    nginx正向代理访问百度地图API
  • 原文地址:https://www.cnblogs.com/kawayi/p/13939147.html
Copyright © 2020-2023  润新知