关于windows使用node.js添加服务器发生的问题(1)
1.首先时windows的ls命令行
windows不能使用直接的ls命令,需要添加一行这样的代码才能用,本人才疏学浅不太懂这是什么意思
C:\D_Demo\web II\CPANEL-ASS2\web_testone>doskey ls=dir
之后才能使用ls工具
C:\D_Demo\web II\CPANEL-ASS2\web_testone 的目录
2022/05/25 09:14 <DIR> .
2022/05/23 15:35 <DIR> ..
2022/05/25 09:15 <DIR> node_modules
2022/05/25 09:15 1,207 package-lock.json
2022/05/25 09:15 280 package.json
2022/05/25 09:13 359 test_server.js
3 个文件 1,846 字节
3 个目录 184,279,855,104 可用字节
2.自建服务器的问题
相比于之前的localhost,其实对于直接的服务器配置就多了几行代码,具体如下:
http请求下的
const http = require('http');
const hostname = '127.0.0.1';
const port = 3030;
const server = http.createServer((req,res) =>{
res.statusCode = 200;
res.setHeader('Content-Type','text/plain');
res.end("Hello world");
});
// .listen(3030);
server.listen(port,hostname,()=>{
console.log('Server running at http://${hostname}')
}
)
https就是把里面的http换位https,
之后再输入的网页地址就换为了
http://127.0.0.1:3030/
如图所示
3.关于命令行的清屏
我们学校告诉我们的是在命令行使用clear工具,但是,现在的windows系统好像对这个地方用不得,所以windows使用的命令是cls
。
第二个是关于输入输出,主要用到的是stdin
标准输入和stdout
标准输出
这是一个读取年份的代码,放在了名为readline.js的文件中
var readline = require('readline');
var ask = readline.createInterface({
input: process.stdin,//标准输入
output: process.stdout//标准输出
});
ask.question(">>What's the year? ", answer => {
//首先打出问题(字符串)
console.log(`Its ${answer}`);
//answer使用上诉的输入输出也就是引入其中的answer
ask.close();
//之后回答完就结束关掉
});
它的Json文件也要有轻微的改动:
{
"name": "readline",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "node readline.js"
<!--这里是注释,要改为start,然后面跟要使用的js文件-->
},
"keywords": [],
"author": "",
"license": "ISC",
"description": ""
}
3.修改文件/在文件中添加信息
这是fsmodule.js的方法
const fs = require('fs');
//声明调用的方法(类似
const data = " ,I love you forever";
//要添加的字符串,变量名data
fs.appendFile('new.txt',data, 'utf8',
// callback function
//添加的文件名,要添加的数据的变量名,数据添加的格式
function(err) {
if (err) throw err;
// if no error
console.log("Successful")
});
结果如下