OSDN Git Service

Regular updates
[twpd/master.git] / nodejs-fs.md
1 ---
2 title: fs
3 category: Node.js
4 layout: 2017/sheet
5 ---
6
7 ### Reading
8
9     fs.readFile('file.txt', function(err, data) { .. });
10     fs.readFile('file.txt', {encoding: 'utf-8'}, function(err, data) { .. });
11
12 ### Writing
13
14     fs.writeFile('output.txt', function(err) { .. });
15     fs.appendFile('output.txt', function(err) { .. });
16
17 ### Watch
18
19     fs.watch('dir OR file.txt', { persistent: true }, function(event, file) {
20       event; /* rename | change */
21     });
22
23 ### Getting info
24
25     fs.exists('file.txt', function(exists /*bool*/) { ... });
26
27     fs.stat('file.txt', function(stats) {
28       stats.isFile();
29       stats.isDirectory();
30       stats.isSymbolicLink();
31     });
32
33 ### File operations
34
35     fs.rename('old.txt', 'new.txt', function(){});
36     fs.chown('file.txt', uid, gid, function(){});
37     fs.symlink('src', 'dest', function(){});
38     fs.unlink('path', function(){});
39     fs.rmdir('path', function(){});
40
41     fs.readdir('path', function(err, files) { .. }); /* `files` = array of names */
42
43 ### Path
44
45     fs.realpath('/etc/passwd', function(err, path) { /* "/private/etc/passwd" */ });
46
47 ### Sync
48
49     data = fs.readFileSync('input.txt');
50     fs.writeFileSync('output.txt', data);
51     fs.appendFileSync('output.txt', data);
52     fs.existsSync('file.txt');
53
54 ### References
55
56 - https://nodejs.org/api/fs.html