美文网首页
01-Node 基础使用

01-Node 基础使用

作者: Am3 | 来源:发表于2019-10-28 08:57 被阅读0次

Node 基础使用

Node 介绍

  • Node 是基于 Chrome V8 引擎的 JavaScript 运行环境
  • Node.js 是由 ECMAScript 和 Node 环境提供的一些附加 API 组成的
  • 在浏览器中全局对象是 window, 在 Node 中全局对象是 global

Node 模块化开发

  • Node 规定一个 JavaScript 文件就是一个模块,模块内部定义的变量和函数默认在外部无法访问
  • 模块内部可以使用 exports 进行成员导出,使用 require 方法导入模块

模块成员的导出

// a.js
// 在模块内部定义方法
const f1 = name => '您好, $(name)';
// 向模块外部导出数据
exports.f1 = f1;

模块成员的导入

// b.js
// 在b.js导入模块 a
const a = require('./a.js');
console.log(a.f1());

Node 系统模块 path 和 fs

系统模块 fs 文件操作

异步读取文件 - readFile()

fs.readFile('文件路径 / 文件名称', ['文件编码'], callback);

// 引入fs模块
const fs = require('fs');
// 异步读取文件
fs.readFile('test.txt', 'utf8', (err, doc)=>{
    if(err!=null){
        return console.log(err);
    }
    console.log(doc)
})

同步读取文件 - readFileSync()

const fs = require('fs');

const result = fs.readFileSync('./01-Node系统模块.md', 'utf8');
console.log(result);

写入文件内容 - writeFile()

fs.writeFile('文件路径 / 文件名称', '文件内容', callback)

const fs = require('fs');
fs.writeFile('./dome.txt', '刚刚写入的文字', err => {
    if (err != null) {
        console.log(err);
        return;
    }
    console.log('写入文件成功')
})

系统模块 path 路径操作

路径拼接

path.join('路径', '路径', '路径')

const path = require('path');
let finialPath = path.join('a', 'b', 'c');
console.log(finialPath); // a\b\c

绝对路径

  • 如果相对路径是相对于命令行工具的目录的话,那么读取文件就要使用绝对路径
  • 使用 __dirname 获取当前文件的绝对路径
const fs = require('fs');
const path = require('path');

fs.readFile(path.join(__dirname, '01.txt'), 'utf8', (err, doc)=>{
    console.log(__dirname);
    console.log(doc);
})

相关文章

网友评论

      本文标题:01-Node 基础使用

      本文链接:https://www.haomeiwen.com/subject/ebsvvctx.html