我的节点代码中不断出现此错误。 DeprecationWarning:不推荐使用不带回调的异步函数

时间:2018-09-17 14:09:31

标签: node.js

我正在尝试在node.js中创建一个小型服务器。不幸的是,它一直给我这个错误。

(node:8412) [DEP0013] DeprecationWarning: Calling an asynchronous function without callback is deprecated.
    fs.js:113
          throw err;  // Forgot a callback but don't know where? Use NODE_DEBUG=fs

基本上,我只是导入所有必需的模块。然后我继续  解析请求以检查请求中的文件名是文件或目录还是服务器上不可用的文件。下面是我的代码:

//include the module http,url,path,fs
const http=require('http');
const url=require('url');
const path=require('path');
const fs=require('fs');

//define the mime types that we would be using  
const mimeTypes={
    "html":"text/html",
    "jpeg":"image/jpeg",
    "jpg":"image/jpg",
    "png":"image/png",
    "js":"text/javascript",
    "css":"text/css"
};

//define the host name to local machine IP 
const hostname='127.0.0.1';

//define the port on which over server would be runnning 
const port = 3000;

//lets create the server  
const server= http.createServer(function(req,resp){
    //get the path name 
    var uri=url.parse(req.url).pathname;
    // get eh file name 
    var filename =path.join(process.cwd(),unescape(uri));
    console.log('loading'+ uri);
    var stats;
    // cehck to see if the file name is actually a file directory or non existant  stuff 
    try{
        stats=fs.lstat(filename);
        if(stats.isFile()){
            var mimeType=mimeType[path.extname(filename).split(".").reverse()[0]];
            resp.writeHead(200,{'Content-Type':mimeType});
            var fileStream = fs.createReadStream(filename);
            fileStream.pipe(resp);
            resp.end(); 
        } else if(stats.isDirectory()){
            resp.writeHead(302,{
                'Location':'index.html'
            });
            resp.end();    
        }
        else{
            resp.writeHead(500,{'Content-Type':'text/plain'});
            resp.write('500 Internal server error \n');
            resp.end();
        }


    }catch(e)
    {
        resp.writeHead(404,{'Content-type':'text/plain'});
        resp.write('404 Not Found \n');
        resp.end();
        return;
    }


}).listen(3000);

//lets create a listner to make sure that the port is running  when the code is called 
server.listen(port,hostname,()=>{
    console.log(`Server running at http://${hostname}:${port}/`);
});

1 个答案:

答案 0 :(得分:1)

fs.lstat是异步调用,您可以添加回叫或使用该调用的同步版本; fs.lstatSync

https://nodejs.org/api/fs.html#fs_fs_lstat_path_options_callback