加入收藏 | 设为首页 | 会员中心 | 我要投稿 常州站长网 (https://www.0519zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 服务器 > 搭建环境 > Linux > 正文

node.js中的fs.truncate方法使用说明

发布时间:2016-11-24 02:37:55 所属栏目:Linux 来源:站长网
导读:方法说明: 文件内容截取操作。 语法: 复制代码 代码如下: fs.truncate(path, len, [callback(err)]) 由于该方法属于fs模块,使用前需要引入fs模块(var fs= require(“fs”) ) 接收参数: pathnbsp;nbsp;nbsp;nbsp;nbsp;nbsp;nbsp;nbsp;nbsp;nbsp; 文件

方法说明:

文件内容截取操作。

语法:

复制代码 代码如下:
fs.truncate(path, len, [callback(err)])

由于该方法属于fs模块,使用前需要引入fs模块(var fs= require(“fs”) )

接收参数:

pathnbsp;nbsp;nbsp;nbsp;nbsp;nbsp;nbsp;nbsp;nbsp;nbsp; 文件路径

lennbsp;nbsp;nbsp;nbsp;nbsp;nbsp;nbsp;nbsp;nbsp;nbsp;nbsp;nbsp;nbsp; 截断长度,只保留该字符长度内的字符,超出部分将被清除。

callbacknbsp;nbsp;nbsp;nbsp;nbsp; 回调,传递一个异常参数err

例子:

复制代码 代码如下:
var fs = require('fs');
fs.truncate('126.txt', 2, function(err){
nbsp;if(err){
nbsp; throw err;
nbsp;}
nbsp;console.log('文件内容截断成功');
})

源码:

复制代码 代码如下:
fs.truncate = function(path, len, callback) {
nbsp; if (util.isNumber(path)) {
nbsp;nbsp;nbsp; // legacy
nbsp;nbsp;nbsp; return fs.ftruncate(path, len, callback);
nbsp; }
nbsp; if (util.isFunction(len)) {
nbsp;nbsp;nbsp; callback = len;
nbsp;nbsp;nbsp; len = 0;
nbsp; } else if (util.isUndefined(len)) {
nbsp;nbsp;nbsp; len = 0;
nbsp; }
nbsp; callback = maybeCallback(callback);
nbsp; fs.open(path, 'r+', function(er, fd) {
nbsp;nbsp;nbsp; if (er) return callback(er);
nbsp;nbsp;nbsp; binding.ftruncate(fd, len, function(er) {
nbsp;nbsp;nbsp;nbsp;nbsp; fs.close(fd, function(er2) {
nbsp;nbsp;nbsp;nbsp;nbsp;nbsp;nbsp; callback(er || er2);
nbsp;nbsp;nbsp;nbsp;nbsp; });
nbsp;nbsp;nbsp; });
nbsp; });
};

(编辑:常州站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读