node.js写入文件踩坑

function writeFile(){
	fs.writeFile("how.html","bye");
	return "write successful";
	
}

报错如下:

 throw new ERR_INVALID_CALLBACK(callback);
    ^

TypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Received undefined
[90m    at maybeCallback (node:fs:174:3)[39m
[90m    at Object.writeFile (node:fs:2091:14)[39m
    at Object.writeFile [as /writeFile] (C:\陆哥\project_nodejs\src\file\requestHandlers.js:10:5)
    at route (C:\陆哥\project_nodejs\src\router\router.js:3:26)
    at Server.onRequest (C:\陆哥\project_nodejs\src\router\server.js:7:12)
[90m    at Server.emit (node:events:394:28)[39m
[90m    at parserOnIncoming (node:_http_server:927:12)[39m
[90m    at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17)[39m {
  code: [32m'ERR_INVALID_CALLBACK'[39m

查了一下发现原来是writeFile调用还需要第三个参数callback

修改如下

function writeFile(){
	fs.writeFile("how.html","bye",function(err,result){
		if(err)
			console.log("error",err);
	});
	return "write successful";
	
}

写入成功

强调的是,还有一个可空的option数组对象

· encoding   (string)            可选值,默认 ‘utf8′,当data使buffer时,该值应该为 ignored。

· mode         (Number)        文件读写权限,默认值 438

· flag            (String)            默认值 ‘w'

你可能感兴趣的:(node.js)