289 node.js系统模块,相对路径、绝对路径



05.readFile.js

// 1.通过模块的名字fs对模块进行引用
const fs = require('fs');

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

const fs = require('fs');

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

  console.log('文件内容写入成功');
})

// public/uploads/avatar
const path = require('path');

const finalPath = path.join('public', 'uploads','avatar');

console.log(finalPath); // public\uploads\avatar

const fs = require('fs');
const path = require('path');

// 当前文件的绝对路径,...\kejian2\11-16.前后端交互\11-13.node+express\day01\code
console.log(__dirname);
// ...\kejian2\11-16.前后端交互\11-13.node+express\day01\code\01.helloworld.js
console.log(path.join(__dirname, '01.helloworld.js'));

fs.readFile(path.join(__dirname, '01.helloworld.js'), 'utf8', (err, doc) => {
  console.log(err)  // null
  console.log(doc)  // 01.helloworld.js 的内容
});

posted on 2020-02-19 10:08  冲啊!  阅读(382)  评论(0编辑  收藏  举报

导航