当前位置:网站首页>fs. Readfile() and fs writeFile()

fs. Readfile() and fs writeFile()

2022-06-21 17:30:00 Yu'an_ ZhangDe

Installation configuration NodeJs Environmental Science

Want to use these two methods , First you need to install the configuration NodeJs Environmental Science , I put the link here , Please go to the rookie tutorial to see the specific tutorial , I won't go into details here .

Node.js Installation configuration | Novice tutorial (runoob.com)

fs.readFile()

fs.readFile() Method , Used to read the contents of the specified file

Usage method

//  Import fs modular 
const fs = require('fs')  //  amount to  <script src='./fs></script>
// 2、fs.readFile(' Path to file ',' Coding format ', Callback function )
// fs.readFile('./test1.js','utf8',(err,data)=>{
fs.readFile('./test.js', 'utf8', (err, data) => {
    //  Read successful  err by null
    //  Read failed  err For the wrong person 
    if (err) return console.log(err.message);
    console.log('==========');
    console.log(data);
})

test.js

console.log('node');
let a = 1
let b = 2
console.log('--------------------------');
console.log(a + b);  //3

Use... On the terminal node Execute this document


fs.writeFile()

fs.writeFile() Method , Used to write content to the specified file  

Usage method

const fs = require('fs')
fs.writeFile('./test.js','Hello world',err => {
    if(err) return console.log(err);
    console.log('===============');
    console.log(' Write successfully ');
})

test.js 

console.log('node');
let a = 1
let b = 2
console.log('--------------------------');
console.log(a + b);  //3

Use... On the terminal node Execute this document

 

Be careful :fs.writeFile()  Is to rewrite the contents of the target file , Will not add... From the original content

 

原网站

版权声明
本文为[Yu'an_ ZhangDe]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206211517547804.html