Stability: 3 - Stable
File System 的每个API都有异步方式和同步方式,两种方式的区别在于异步方式具有一个回调函数,并且这个回调函数的第一个参数为
err
,如果操作成功,这个参数为null
或undefined
rename : 改名
fs.rename(oldPath, newPath, callback)
//Asynchronous rename
fs.rename('/path/demo.txt', '/path/demo1.txt', function (err) {
if (err) {
throw err;
}
console.log('renamed complete');
});
fs.renameSync(oldPath, newPath)
//Synchronous rename
fs.renameSync('path/demo.txt', '/path/demo1.txt');
ftruncate : 截断文件(fd)
fs.ftruncate(fd, len, callback)
//Asynchronous ftruncate
fs.open('/path/demo1.txt', 'a', function (err, fd) {
if (err) {
throw err;
}
fs.ftruncate(fd, 50, function (err) {
if (err) {
throw err;
}
console.log(fd);
fs.close(fd, function () {
console.log('Done');
});
});
});
fs.ftruncateSync(fd, len)
//Synchronous ftruncate
var fd = fs.openSync('/path/demo1.txt', 'a');
fs.ftruncateSync(fd, 50);
console.log(fd);
fs.closeSync(fd);
console.log('Done');
truncate : 截断文件(path)
fs.truncate(path, len, callback)
//Asynchronous truncate
fs.open('/path/demo1.txt', 'r+', function (err, fd) {
if (err) {
throw err;
}
fs.truncate('/path/demo1.txt', 10, function (err) {
if (err) {
throw err;
}
console.log(fd);
fs.close(fd, function () {
console.log('Done');
});
});
});
fs.truncateSync(path, len)
//Synchronous truncate
var fd = fs.openSync('/path/demo1.txt', 'r+');
fs.truncateSync('/path/demo1.txt', 5);
console.log(fd);
fs.close(fd);
console.log('Done');