我试图在NodeJS中创建一个脚本,它返回文本文件的前两行.
我目前正在使用此代码:
// content of index.js
const fs = require('fs')
const readline = require('readline');
const http = require('http')
const port = 8080
String.prototype.beginsWith = function (string) {
return(this.indexOf(string) === 0);
};
const requestHandler = (request, response) => {
console.log(request.url)
if (request.url == "/newlines") {
filename = "allnames.txt"
readline.createInterface({
input: fs.createReadStream(filename),
output: process.stdout
})
response.end('Hello Node.js Server!')
}
else {
response.end('Go away!')
}
}
const server = http.createServer(requestHandler)
server.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
} …Run Code Online (Sandbox Code Playgroud) node.js ×1