nodejsファイル操作
14844 ワード
****ファイル操作モジュールは、オペレーティングシステム命令の代わりに完全に********できます.
1.****nodejs 。 Sync
//
fs.unlink('/tmp/hello', (err) => {
if (err) throw err;
console.log('successfully deleted /tmp/hello');
});
//
fs.unlinkSync('/tmp/hello');
console.log('successfully deleted /tmp/hello');
2.**
fs.rename('/tmp/hello', '/tmp/world', (err) => {
if (err) throw err;
console.log('renamed complete');
});
fs.stat('/tmp/world', (err, stats) => {
if (err) throw err;
console.log(`stats: ${JSON.stringify(stats)}`);
//stats: {"dev":-593730986,"mode":33206,"nlink":1,"uid":0,"gid":0,
//"rdev":0,"ino":2251799813714667,"size":3,"atime":"2016-03-25T07:41:15.892Z",
//"mtime":"2016-03-25T07:41:19.870Z","ctime":"2016-03-25T07:42:00.065Z",
//"birthtime":"2016-03-25T07:41:15.819Z"}
});
//
fs.rename('/tmp/hello', '/tmp/world', (err) => {
if (err) throw err;
fs.stat('/tmp/world', (err, stats) => {
if (err) throw err;
console.log(`stats: ${JSON.stringify(stats)}`);
});
});
4.Class: fs.FSWatcher , fs.watch()
(1)Event: 'change'
event
filename
(2)Event: 'error'
(3)watcher.close()
5.Class: fs.ReadStream
(1)Event: 'open' fd
ReadStream
(2)readStream.path
6.***Class: fs.Stats
(1) fs.stat(), fs.lstat()、 fs.fstat()
stats.isFile()
stats.isDirectory()
stats.isBlockDevice()
stats.isCharacterDevice()
stats.isSymbolicLink() (only valid with fs.lstat())
stats.isFIFO()
stats.isSocket()
//
fs.stat('input.txt', function (err, stats) {
if (err) {
return console.error(err);
}
console.log(stats);
console.log(" !");
//
console.log(" (isFile) ? " + stats.isFile());
console.log(" (isDirectory) ? " + stats.isDirectory());
});
(2) util.inspect(stats)
{
dev: 2114,
ino: 48064969,
mode: 33188,
nlink: 1,
uid: 85,
gid: 100,
rdev: 0,
size: 527,
blksize: 4096,
blocks: 8,
atime: Mon, 10 Oct 2011 23:24:11 GMT, //Access Time"
mtime: Mon, 10 Oct 2011 23:24:11 GMT, //Modified Time
ctime: Mon, 10 Oct 2011 23:24:11 GMT, //Change Time status
birthtime: Mon, 10 Oct 2011 23:24:11 GMT //
}
7.Class: fs.WriteStream
(1)Event: 'open' fd
WriteStream
(2)writeStream.bytesWritten
(3)writeStream.path
8.fs.access(path[, mode], callback)
(1)mode
fs.F_OK - , , rwx
fs.R_OK -
fs.W_OK -
fs.X_OK - Windows (will behave like fs.F_OK).
(2)
fs.access('/etc/passwd', fs.R_OK | fs.W_OK, (err) => {
console.log(err ? 'no access!' : 'can read/write');
});
(3) ,
fs.accessSync(path[, mode])
9.***fs.appendFile(file, data[, options], callback)
(1)
file | filename file descriptor
data |
options