记录 Node 写入和读取文件的简单方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* * Author: wxnacy([email protected])
* * Description:
* */
const fs = require('fs');

fs.writeFile('/tmp/test', 'Hello World', function(err, data) {
if( err ){
return console.log(err);
}
console.log(data);
})

fs.readFile('/tmp/test', 'utf8', (err, data) => {
if( err ){
return console.log(err);
}
console.log(data);
})

将读取改为同步调用方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* * Author: wxnacy([email protected])
* * Description:
* */
const fs = require('fs');

const path = '/Users/wxnacy/Downloads/test.sh'

async function read() {
return new Promise((resolve, reject) => {
fs.readFile(path, 'utf8', (err, data) => {
if( err ){
reject(err)
}
resolve(data)
})
})
}

(async () => {

try {

let data = await read()
console.log(data);
} catch (e) {
console.log(e);

}

})();
03-16 11:53