无法使用' http'提供html文件Node.js的模块

时间:2018-01-23 10:41:15

标签: javascript angularjs node.js http response

我正在尝试将html页面作为对' /'的回复。在我的http服务器上请求。 但不知怎的,它不起作用。

我的index.html是 -

<html>
<head>
    <title>File Explorer</title>
    <link rel='stylesheet' href='/stylesheets/style.css'/>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.13/semantic.min.css"/>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.js"></script>

</head>

<script>
    var fileExplorerApp = angular.module('explorerApp', []);
    fileExplorerApp.controller("MyController", function ($scope, $http) {
        var currentPath = '';
        $scope.reload = function (newPath, back) {
            if (back) {
                currentPath = newPath;
            } else {
                if (currentPath === '') {
                    currentPath = newPath;
                } else {
                    currentPath = currentPath + '/' + newPath;
                }
            }
            console.log('Newpath- ' + currentPath);
            $http.get('http://localhost:3000/list_dir?path=' + currentPath)
                .then(function (response) {
                    $scope.filesAndFolders = response.data;
                    $scope.currentPath = currentPath;
                }, function (error) {
                    console.log('Error in $http- ' + error);
                });    
        }

        $scope.back = function () {
            var prevPath = currentPath.substring(0, currentPath.lastIndexOf('/'));
            console.log('Path after substring- ' + prevPath);
            console.log('Prevpath when back clicked- ' + prevPath);
            $scope.reload(prevPath, true);

        }

        $scope.reload('F:/', false);
    });
</script>

<body ng-app="explorerApp" ng-controller="MyController">

<div class="ui container">
    <h1 id="currentPath">Current Directory- {{ currentPath }}</h1>
    <button ng-if="currentPath !== 'F:/'"
            ng-click="back()"
            class="ui left labeled icon button">
        <i class="left arrow icon"></i>
        Back
    </button>
    <div class="ui list">
        <a class="item"
           ng-repeat="item in filesAndFolders"
           ng-click="reload(item.name, false)"
           ng-href="{{item.type === 'file' ? '/get_file?path='+currentPath+'/'+item.name : ''}}">
            <i ng-if="item.type === 'folder'" class="folder icon"></i>
            <i ng-if="item.type === 'file'" class="file icon"></i>
            {{ item.name }}</a>
    </div>
</div>
</body>
</html>

通过角度我访问另一条路线&#39; / list_dir&#39;并使用&#39; http&#39;处理请求Node.js的模块(Not Express)。

if(parsedUrl.pathname === '/list_dir') {
            console.log('I\'m here');
            var file_path = parsedUrl.query['path'];
            list_dir.listDir(file_path, function (err, data) {
                if(err){
                    res.writeHeader(400, {'Content-Type':'text/json'});
                    res.write(err);
                } else {
                    console.log('in list_dir, no errors- response is- '+data);
                    res.writeHeader(200,{'Contenttype':'application/json'});
                    res.write(JSON.stringify(data));
                }
            });
            res.end();
            break;
        }

路线&#39; / list_dir&#39;然后访问另一个脚本中的函数 -

module.exports = {
listDir: function (path, myCallback) {
    var resultObj = [];

    fs.readdir(path, function (err, data) {
        console.log('In listDir');
        if (err) {
            switch(err.code){
                case 'EACCES':
                    return myCallback({errno: err.errno, description: 'An attempt was made to access a file in a way forbidden by its file access permissions.'}, null);
                case 'ENOENT':
                    return myCallback({errno: err.errno, description: 'The specified path does not exist.'});
                case 'EPERM':
                    return myCallback({errno: err.errno, description: 'An attempt was made to perform an operation that requires elevated privileges.'})
                case 'ENOTDIR':
                    return myCallback({errno: err.errno, description: 'The specified path is not a directory.'})
            }
            return myCallback(err, null);
        }

        var itemsCompleted = 0;
        data.forEach(function (value) {
            fs.lstat(path + '/' + value, function (err, stats) {
                itemsCompleted++;
                if (err) {
                    console.log(err);
                } else {
                    if (stats.isFile()) {
                        resultObj.push({
                            type: 'file',
                            name: value,
                            size: stats['size']
                        });
                        //resultObj.push(value);
                        //console.log(resultObj + '\n');
                    } else if (stats.isDirectory()) {
                        resultObj.push({
                            type: 'folder',
                            name: value,
                            size: stats['size']
                        });
                    }
                }

                if (itemsCompleted >= data.length) {
                    //console.log(resultObj);
                    return myCallback(null, resultObj)
                }
            });
        });
    });
}

};

此函数返回给定路径中所有文件/文件夹的json对象,该对象将提供给&#39; / list_dir&#39;路线。但我没有得到正确的回应。

我希望此路由使用listDir函数返回的相同json进行响应。我是Node.js的http模块的新手,也许我写了错误的标题或者我以错误的方式消费数据。请帮忙。谢谢!

更新:

Chirags的答案是正确的,现在&#39; / list_dir&#39; route返回正确的json响应。但是,我仍然无法提供index.html文件,我使用AngularJS来使用此路线。

这就是我处理路线的方式 -

if (parsedUrl.pathname === '/') {
    fs.readFile('./index.html', 'utf-8', function (err, fileResponse) {
        if (err) {
            console.log('Error');
            res.writeHeader(404, {
                "Content-Type": "text/html"
            });
            res.write('There was an error!');
        } else {
            console.log('No error');
            res.writeHeader(200, {
                "Content-Type": "text/html"
            });
            res.write(fileResponse);
        }
        res.end();
    });
}

这有什么不对吗?

1 个答案:

答案 0 :(得分:0)

您过早关闭了响应流。基本上,res.end()在异步函数执行之前执行,以读取目录并执行回调。尝试:

if (parsedUrl.pathname === '/list_dir') {
    console.log('I\'m here');
    var file_path = parsedUrl.query['path'];
    list_dir.listDir(file_path, function (err, data) {
        if (err) {
            res.writeHeader(400, {
                'Content-Type': 'text/json'
            });
            res.write(err);
        } else {
            console.log('in list_dir, no errors- response is- ' + data);
            res.writeHeader(200, {
                'Contenttype': 'application/json'
            });
            res.write(JSON.stringify(data));
        }
        res.end();
    });
    break;
}