在 Node.js 中比较两个文件的好方法是什么

我正在尝试构建一个简单的自动分级器来检查两个 javascript 匹配文件。


这是一个可能的练习示例:


var http = require('http');

http.createServer((req, res) => {

  res.writeHead(200, {'Content-Type': 'text/plain'});

  res.end('Hello World!');

}).listen(8000,  () => {

console.log('Node server is running..');

});

这是上述练习的解决方案:


var http = require('http');

var dt = require('./myfirstmodule');


http.createServer((req, res) => {

  res.writeHead(200, {'Content-Type': 'text/plain'});

  res.write("The date and time are currently: " + dt.myDateTime());

  res.end('Hello World!');

}).listen(8000,  () => {

console.log('Node server is running..');

});

你知道在 Node 中检查练习文件是否与解决方案匹配的好方法吗?完全匹配文件可能不是一个好主意,因为它们之间可能存在空格并且仍然是一个有效的解决方案。


提前致谢。


守候你守候我
浏览 780回答 1
1回答

蓝山帝景

您可以使用读取每个文件的内容,fs.readFileSync()然后使用包字符串相似度来比较它们。安装字符串相似度:npm install string-similarity --save然后在你的代码中:const fs = require('fs');const stringSimilarity = require('string-similarity');let exercise = fs.readFileSync('path/to/file/exercise.js');let solution = fs.readFileSync('path/to/file/solution.js');var similarity = stringSimilarity.compareTwoStrings(exercise, solution);console.log(similarity); //Returns a fraction between 0 and 1
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript