本文介绍了检查writeFileSync是否成功写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我有一个用 express.js 定义的简单路由:

I have a simple route defined with express.js:

exports.save = function (request, response)
{
    var file = request.body.file;
    var content = request.body.content;

    var saved = false;

    if (fs.existsSync( file ))
    {
        saved = fs.writeFileSync(file, content, 'utf8');
    }

    console.log( saved ); // undefined or false, never true

    response.send(saved ? 200 : 500, saved ? 'saved' : 'error'); // 500, error
};

if(保存的typeof ==='undefined')是否为true; 是唯一的选择吗?感觉很hacky.

Is if (typeof saved === 'undefined') saved = true; the only option? Feels hacky.

推荐答案

根据node.js 源代码 fs.writeFileSync 不返回任何内容.

According to node.js source-code fs.writeFileSync doesn't return anything.

如果出现问题,它将引发 Error 对象.因此,您应该在 try-catch 块中编写 fs.writeFileSync(file,content,'utf8'); .

It throws an Error object if something goes wrong. So you should write fs.writeFileSync(file, content, 'utf8'); within a try-catch block.

这篇关于检查writeFileSync是否成功写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 22:23