OSDN Git Service

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