Today backend colleagues from work and wanted me to read the contents of a file. I think this is a small Manga, he immediately agreed.
I know this is nodejs read, but I want to, usually we have to be able to run from a service node server,
such as the following code
var http = require('http');
http.createServer(function(request,response){
response.writeHead(200,{'Content-Type':'text/plain'});//200是服务器响应头部
response.end('hello world!')
}).listen(8888);
console.log('在控制台打印出....http://127.0.0.1:8888/')
Print in the browser, running
but the file how to read it?
Nodejs have a special module, fs, fs module but will not play a service ah?
This time we will npm With the magic of the
first step:
npm init
cnpm install --save fs
Write
//app.js
const fs = require('fs');
try {
const data = fs.readFileSync('./rootca.pem', 'utf-8');
// 等待操作结果返回,然后打印结果
console.log(data);
} catch(e) {
console.log('读取文件发生错误');
Run
node app.js
operating results for the
bingo completed my colleagues to help small busy
then I think my face inward, someone said to me, I thank you more embarrassed ah, I'm going to file written're welcome
const fs = require('fs');
var str = '不用谢';
// fs.writeFileSync('./rootca.pem',str,(err)=>{
// if(err){
// console.log('写入文件操作失败')
// }else{
// console.log('写入文件操作成功')
// }
// })
try {
const data = fs.readFileSync('./rootca.pem', 'utf-8');
// 等待操作结果返回,然后打印结果
console.log(data);
} catch(e) {
console.log('读取文件发生错误');
}
We will find're welcome written into the file, but the file is rewritten
first come here, see next blog