尝试在nodejs服务器上的文本文件(11,22,33,44)中对数字进行求和,我通过在url中输入一系列数字让它们如下图所示,但是我需要它能够输入/读取文件,如html中的输入标签,然后在浏览器中打印结果..这在节点中是否可行?甚至在url中键入文件路径/名称
working screenshot of using url by manual input
s.js文件
const http = require('http')
const fs = require('fs')
let inFile = process.argv[2]
let outFile = process.argv[3]
console.log(inFile, outFile)
function sum (allNumbers) {
return allNumbers.reduce( (s,x) => s += x)
}
const server = http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/html"})
// INPUT PROCESSING
response.write('<h1>Hello!</h1><p>You asked for <code>' + request.url + '</code></p>')
console.log(request.url)
// find characters after ?
let dataStart = request.url.indexOf('?') + 1
let dataString = request.url.slice(dataStart)
// transform to array at the commas
let arrayOfStrings = dataString.split(',')
// convert to numbers
let arrayOfNumbers = arrayOfStrings.map(s => Number(s))
// CALCULATIONS
let s = sum(arrayOfNumbers)
// OUTPUT PROCESSING
response.write( arrayOfNumbers + "<p>");
response.write( 'sum=' + s + '<p>')
let result = {'data': arrayOfNumbers, 'sum': s}
result = JSON.stringify(result)
response.write(result)
response.write('bye for now');
response.end();
})
server.listen(8000);