先写三个txt文件,分别为1.txt
、2.txt
、3.txt
要求:将1
和2
中的内容链接然后放入3
中
const fs = require('fs')
const path = require('path')
fs.readFile(path.join(__dirname,'/1.txt'),(error,data)=>{
if(error){
console.log('1读取失败')
}
else{
fs.readFile(path.join(__dirname,'/2.txt'),(err,data2)=>{
if(err){
console.log('2读取失败')
}
else{
fs.writeFile(path.join(__dirname,'/3.txt'),data.toString() + data2.toString(),(e,d)=>{
if(e){
console.log('3读取失败')
}
else{
console.log('success')
}
})
}
})
}
})
Promise:
function fsfun(method, address){
return new Promise(function(reject,resolve){
fs.readFile(address, function(error,data){
if(error){
reject(error)
}
else{
resolve(data)
}
})
})
}
fsfun( path.join(__dirname,'/1.txt')).then(res =>{
console.log(res.toString())
return fsfun( path.join(__dirname,'/2.txt'))
}).then(res=>{
console.log('2',res)
}).catch(err=>{
console.log(err)
})