什么是比较 Node.js 中的两个文件的好解决方案

What would be a good solution to compare two files in 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中检查练习文件是否匹配解决方案的好解决方案吗?完全匹配文件可能不是一个好主意,因为它们之间可能有空格,但仍然是一个有效的解决方案。

提前致谢。

安德里亚

您可以使用 fs.readFileSync() then use the package string similarity 读取每个文件的内容以进行比较。

安装字符串相似度:

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