【问题标题】:What would be a good solution to compare two files in Node.js什么是比较 Node.js 中的两个文件的好解决方案
【发布时间】:2019-11-11 18:59:28
【问题描述】:

我正在尝试构建一个简单的自动评分器来检查两个 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 中检查练习文件是否匹配解决方案的好方法吗?完全匹配文件可能不是一个好主意,因为它们之间可能存在空格,但仍然是一个有效的解决方案。

提前致谢。

安德烈亚

【问题讨论】:

  • 检查代码本身而不是生成的结果不是“简单自动评分器”。你可以用不同的代码和不同的 AST-s 编写多个程序来做同样的事情。改为测试功能。

标签: javascript node.js file fs


【解决方案1】:

您可以使用fs.readFileSync() 读取每个文件内容,然后使用包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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-17
    • 2021-05-20
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多