gpt4 book ai didi

javascript - 用 Javascript 编写的脚本不会自行终止?

转载 作者:行者123 更新时间:2023-12-03 06:38:17 28 4
gpt4 key购买 nike

嗨,我编写了一个具有递归函数的脚本,该函数采用路径并解析目录结构。该脚本按预期工作,但不会自行终止。脚本是用 Javascript 编写的,它使用 NodeJs 模块,如 fs(文件系统)和路径。

我的代码:

var parseDirectory = function(currPath, tags, func){
var util = util || require('./util');
var fs = fs || require('fs');
var path = path || require('path');
if(!util.fileExist(currPath)) {
throw new Error('Path is invalid, it does not exist.');
}

//get the stat and do operation according to file type
var stat = fs.statSync(currPath);

//if directory
// - get all files inside the directory
// - push the currPath in tags
// - call parseDirectory for each file
// - pop from the tags array
if(stat.isDirectory()) {
var files = fs.readdirSync(currPath);
var fs = fs || require('fs');
tags.push(path.parse(currPath).name);
files.forEach(function(file) {
parseDirectory(path.join(currPath,file),tags,func);
});
tags.pop();
} else if(stat.isFile()) {
func(currPath,tags);
} else {
throw new Error('Path is not a file or Directory');
}
}

//connect to db
var mongoose = mongoose || require('mongoose');
mongoose.connect('mongodb://localhost:27017/iconrepo');

// a sample call to parseDirectory
parseDirectory('icon/png/',[],function(filePath, tags) {
var path = path || require('path');
var fs = fs || require('fs');
var File = require('./models/file');
var stat = fs.statSync(filePath);

var file = new File({
name : path.parse(filePath).name,
type : path.extname(filePath),
size : stat.size,
tags : tags,
path : filePath
});

//console.log(file);
//file.save(function(err) {
// if(err) {
// throw new Error(err);
// }

// console.log('Added ', filePath);
//});

console.log('Exiting Callback for filePath',filePath);
});

console.log('Last statement of the script');

文件.js

// a file schema file

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var fileSchema = new Schema({
name: String,
type: String,
size: {type: Number},
tags: [String],
path: String
});

module.exports = mongoose.model('File',fileSchema);
// a file schema file

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var fileSchema = new Schema({
name: String,
type: String,
size: {type: Number},
tags: [String],
path: String
});

module.exports = mongoose.model('File',fileSchema);

谁能指出我犯了什么错误。

最佳答案

Mongoose 建立了一个连接,使您的脚本保持运行。

调用 mongoose.connection.close() 结束脚本。

关于javascript - 用 Javascript 编写的脚本不会自行终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38089172/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com